python加载动态库_引用 加载动态库(.so) 文件

[TOC]

> [参考](http://www.bkjia.com/Linux/964805.html)

## 创建一个 .so 文件

## 1. 创建`hello.c`

```

int hello_add(int a, int b)

{

return a + b;

}

```

## 2. 编译

```

$ gcc -O -c -fPIC -o hello.o hello.c

$ gcc -shared -o libhello.so hello.o

$ su

# echo /usr/local/lib > /etc/ld.so.conf.d/local.conf

# cp libhello.so /usr/local/lib

# /sbin/ldconfig

```

## 3. 验证是否正确加载

创建 `hellotest.c`

```

#include

int main()

{

int a = 3, b = 4;

printf("%d + %d = %d\n", a, b, hello_add(a,b));

return 0;

}

```

执行

```

$ gcc -o hellotest -lhello hellotest.c # -lhello 编译时加入动态so 文件

$ ./hellotest

3 + 4 = 7

```

> 在 CentOS 下可以正常编译

## 4. 下载php 源码

进入`ext`

```

$ ./ext_skel --extname=hello

$ cd hello

```

## 5. 修改 `config.m4`

`去掉第16行和第18行的注释(注释符号为 dnl )`

```

16: PHP_ARG_ENABLE(hello, whether to enable hello support,

17: dnl Make sure that the comment is aligned:

18: [ --enable-hello Enable hello support])

```

```

$ phpize

```

## 6. 修改` php_hello.h`

在文件后尾添加

```

PHP_FUNCTION(hello_add);

```

## 7. 编辑`hello.c`

```

zend_function_entry hello_functions[] = {

PHP_FE(confirm_hello_compiled, NULL) /* For testing, remove later. */

PHP_FE(hello_add, NULL) /* 此处添加要实现的方法 */

{NULL, NULL, NULL} /* Must be the last line in hello_functions[] */

};

//文末,添加具体实现

PHP_FUNCTION(hello_add)

{

longint a, b;

longint result;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &a, &b) == FAILURE) {

return;

}

result = hello_add(a, b);

RETURN_LONG(result);

}

```

## 8. 编译安装

```

$ phpize

$ ./configure --with-php-config=/www/server/php/56/bin/php-config

$ make clean # 清除编译

$ make LDFLAGS=-lhello #-lhello 表示加载 动态库 libhello.so 文件

$ sudo make install

```

在`php.ini`加入`extension=hello.so`

## 9. 测试

`php -r"echo hello_add(3, 4);"` //输出7

或者使用`php hello.php`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值