Python 调用 so

先来一个网上随便都能找得到的例子吧:先来一个test.c

#include "test.h"

void test(){
  printf("hello so\n");
}

float add(float a, float b){
  return a+b;
}

在来一个test.h:

#include "stdio.h"

void test();
float add(float, float);

然后将其编译成.so文件:

gcc -fPIC -shared test.c -o libtest.so

最后在python文件里面调用:

#!/usr/bin/env python                                                                                                                   

print "start call  so file\n"

from ctypes import *

test = cdll.LoadLibrary("./libtest.so")

test.test()
add =test.add
add.argtypes =[c_float, c_float] 
add.restype =c_float
print add(1.3, 13.4)

然后在终端运行:

root@localhost:~/python/call_so# python test.py
start call so file
hello so
14.6999998093

嗯,python2的这个数字精度的bug也是醉了

当然了,ctypes不是这样简单的模块,否则也不会放到标准库里面去

(未完待续。。。)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容