3568

初试swig编写php扩展

乐果   发表于   2015 年 05 月 13 日 标签:swigPHP

先写一段C代码:

#include <stdio.h>
#include <string.h>

char *hello(char *s)
{
    int num = strlen(s);
    //printf("string len is %i",num);
    char ns[num];
    int i;
    for(i=0; i<num; i++)
    {
        ns[(num-1)-i] = s[i];
    }
    char *result = ns;
    return result;
}

代码意思很简单喔,就是一个hello函数,该函数的作用是接收一个字符串参数,把字符串进行反转,然后返回。

现在,针对这个c函数,把它加入php的扩展(动态库方式),步骤如下:

1、将c的源文件编译成目标文件

cc -fpic -c hello.c

2、编写swig翻译文件hello.i

%module hello

%{
    extern char *hello(char *s);
%}

extern char *hello(char *s);

3、执行swig命令,生成相应的其他目标语言的过渡文件

swig -php hello.i

4、编译过渡文件(c源文件),生成目标文件

gcc `/data/service/php54/bin/php-config --includes` -fpic -c hello_wrap.c
//假设我们的php是编译安装
//并且安装的路径为/data/service/php54

5、将目标文件(第1、4步骤生成的目标文件)链接生成动态库文件。

gcc -shared *.o -o hello.so

6、配置php,载入hello.so(略)

乐果   发表于   2015 年 05 月 13 日 标签:swigPHP

0

文章评论