Home  >  Article  >  Backend Development  >  C 编撰动态链接库PHP DLL

C 编撰动态链接库PHP DLL

WBOY
WBOYOriginal
2016-06-13 10:38:171075browse

C 编写动态链接库PHP DLL

新建-》工程-》win32 Dynamic Link Library->一个简单的dll工程

只有在函数前标注:extern? ?"C"? ?_declspec(dllexport) 的函数才能被其他的程序通过dll的方式调用

extern "C" _declspec(dllexport) int add(int i1,int i2){	return i1+i2;}

(1) 静态链接声明:

#pragma comment(lib, "dll1.lib")extern   "C"   _declspec(dllexport) int add(int i1,int i2);

?然后就可以像调用普通函数一样调用了。如果dll中函数很多的话,一般都是由dll开发者开发好.h文件,把函数的声明都写好,然后供其他人调用,只要include就好了。


(2) 动态链接:
//__cdecl __stdcall 等不同的调用约定,也就是参数的压栈顺序等,暂时不用关心,只要保证调用的时候和dll中的调用约定一样就可以。

声明函数指针 typedef int(__cdecl*? FunctionAdd)(int,int);

#include "stdafx.h"typedef int(__cdecl*  FunctionAdd)(int,int);HMODULE   hModule;   //申明句柄FunctionAdd   add;   //申明指针hModule   =   LoadLibrary("dll1.dll");//调试时hModule为0x10000000   If(NULL==hModule){  //error.}add   =(FunctionAdd)GetProcAddress(hModule,"add");   If(NULL==add){  //error}int r = add(1,1);  FreeLibrary(hModule);  //释放句柄

静态链接和动态链接的区别:静态链接在程序启动的时候就会去检查dll是否存在,如果不存在在启动的时候就会报错,程序无法启动;动态链接是在运行到的时候才会去检查是否存在,而且可以由程序员决定在dll不存在的时候判断逻辑。
要区分静态库、动态库。静态调用dll和动态调用dll。

?

3、 插件机制。
将你编程中经常用到的重复性代码封装成dll,当程序启动时加载你新增的dll使其具备新的功能,如PHP的ext dll

?

windows下手动编译PHP DLL 扩展(亲测)

前提php扩展骨架已经ok

1、php源码包和windows下的二进制包,以及安装Visual C++,并把Microsoft Visual Studio\Common\MSDev98\Bin的绝对路径添加到windows环境变量
2、解压源码包到d:\php_src
3、进入d:\php_src\ext源码包目录,复制skeleton文件夹,并重命名为要开发扩展的名字,本例为“linvo”
4、把二进制包中dev目录下的php5ts.lib文件,拷入新建的linvo目录
5、重命名php_skeleton.h为php_linvo.h,skeleton.c为linvo.c,skeleton.dsp为linvo.dsp,编辑linvo目录中的php_linvo.h、linvo.c、linvo.dsp这三个文件,替换内容中所有extname为linvo,EXTNAME为LINVO。(严格区分大小写
6、编辑php_linvo.h文件(头文件)
在PHP_FUNCTION(confirm_linvo_compiled);下面编写PHP_FUNCTION(hello);声明一个hello函数

7、编辑linvo.c文件(主文件)
在PHP_FE(confirm_linvo_compiled,??? NULL)下面编写
PHP_FE(hello,??? NULL)
这是函数入口,下面该写函数主体了
找到PHP_FUNCTION(confirm_linvo_compiled)函数,该函数是测试函数,在该函数后面新写一个函数

PHP_FUNCTION(hello){    char *arg = NULL;    int arg_len, len;    char *strg;    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {        return;    }    len = spprintf(&strg, 0, "Hello,%s", arg);    RETURN_STRINGL(strg, len, 0);}

?

编译:
8、运行cmd命令行,进入d:\php_src\ext\linvo目录
9、输入 msdev linvo.dsp /MAKE "linvo - Win32 Release_TS"
10、如果没有错误,则在php_src目录下会生成一个Release_TS文件夹,里面就是编译好的php_linvo.dll扩展

?

使用:
11、将其拷入运行环境中的php扩展目录ext
12、编辑php.ini添加extension=php_linvo.dll,重启apache
13、在php文件中执行如下语句
echo hello('Linvo');
将输出
Hello,Linvo
14、通过echo phpinfo();也可看到扩展已加载的信息

?

通过VC6打开项目空间文件编译DLL,此时会php_stream_transport.h报错
d:\php_src\main\streams\php_stream_transport.h需要通过添加typedef int socklen_t;到文件中,便可通过编译

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn