php - 如何在 Zend PHP 扩展中连接外部 C/C++ 库

标签 php c php-internals

我正在尝试使用 Zend 框架制作一个用 C 语言编写的 .so PHP 扩展。使用独立扩展一切正常。但是,如果我尝试在我的扩展中使用其他一些动态链接库,则会出现以下错误:

PHP Warning:  dl(): Unable to load dynamic library '/usr/lib/php5/20121212/test.so' - /usr/lib/php5/20121212/test.so: undefined symbol: _Z5hellov in /var/www/test.php on line 2
PHP Fatal error:  Call to undefined function my_function() in /var/www/test.php on line 3

我已经编译好了libhello.so复制到同目录/usr/lib/php5/20121212/ 我如何从 test.so 模块中使用它?

这是源代码:

测试.c:

#include "php.h"
#include "hello.h"

ZEND_FUNCTION( my_function );
ZEND_FUNCTION(Hello);

zend_function_entry firstmod_functions[] =
{
ZEND_FE(my_function, NULL)
    ZEND_FE(Hello, NULL)
    {NULL, NULL, NULL}
};

zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES
};

ZEND_GET_MODULE(firstmod)

ZEND_FUNCTION( my_function )
{
    char *str; int str_len;
    long l;
    if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT; 

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl", 
        &str, &str_len, &l) == FAILURE) {
        return;
    }

    zend_printf("%s  \r\n", str);
    zend_printf("%ld \r\n", l);

    RETURN_LONG(1);

}

ZEND_FUNCTION (Hello) {
    hello();
}

你好.h:

#include <stdio.h>

void hello();

你好.c:

#include "hello.h"

void hello () {
printf("%s\n", "Hello, world!");
}

测试.php:

<?php
dl("test.so");
my_function("123",12);
    Hello();
?> 

最佳答案

为了让一个函数对 php userland 可见,你需要使用宏 PHP_FUNCTION():

你好.h:

PHP_FUNCTION(hello_world);

测试.c:

ZEND_BEGIN_ARG_INFO_EX(arginfo_hello_world, 0, 0, 2)
    ZEND_ARG_INFO(0, arg1_name)
    ZEND_ARG_INFO(0, arg2_name)
ZEND_END_ARG_INFO()


...


const zend_function_entry pcap_functions[] = { 
    ...
    PHP_FE(my_function, arginfo_hello_world)
    ...
};


...
PHP_FUNCTION( my_function )
{
    char *str; int str_len;
    long l;
    if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT; 

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl", 
        &str, &str_len, &l) == FAILURE) {
        return;
    }

    zend_printf("%s  \r\n", str);
    zend_printf("%ld \r\n", l);

    RETURN_LONG(1);

}

...

关于php - 如何在 Zend PHP 扩展中连接外部 C/C++ 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20002874/

相关文章:

javascript - 衡量用户在网站访问期间花费的时间

c - ARM板什么时候安装操作系统?调用端口地址会映射到真实地址还是虚拟地址?

php - 为什么当 PHP 数组的元素是引用分配时它会被修改?

php - WooCommerce 密码强度更改为 6 个字符

php - 如何使用 wordpress 在 CPanel 中增加 Max_file_upload_size

php - 在php中计算地球上两个坐标之间的行驶距离

c - 在 Linux 上实现 posix_spawn

c - 使指针数组中的所有指针指向 C 中的同一事物?

php - PHP 解释器是否消除死条件?

PHP7哈希表内部结构