一、问题
Python提供的ctypes库,它提供同C语言兼容的数据类型,可以很方便地调用C语言动态链接库中的函数。ctypes 的官方文档可以参考:https://docs.python.org/2/library/ctypes.html
二、Python调用C/C++
1、Python调用C动态链接库的简单例子:
Python调用C库比较简单,不经过任何封装打包成so,再使用python的ctypes调用即可。
(1)C语言文件:pycall.c
/***gcc -o libpycall.so -shared -fPIC pycall.c*/
#include <stdio.h>
#include <stdlib.h>
int foo(int a, int b)
{
printf("you input %d and %d\n", a, b);
return a+b;
}
(2)gcc编译生成动态库libpycall.so:gcc -o libpycall.so -shared -fPIC pycall.c。使用g++编译生成C动态库的代码中的函数或者方法时,需要使用extern "C"来进行编译。
(3)Python调用动态库的文件:pycall.py
import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll("./libpycall.so")
lib.foo(1, 3)
print '***finish***'
(4)运行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/cf61047a8eedfcbea9e3ee8b558548d2.png)
2、Python调用C/C++接口需要类型匹配的例子、
(1)、c语言头文件和源文件ctest.h、ctest.c
/******************************************ctest.h**********************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
struct segment{
int key;
}
struct content{
struct segment seg;
int value
}
struct content g_conent;
int set_kv(int key,int value);
struct content *get_content();
/********************************************ctest.c***********************************/
#include "ctest.h"
int set_kv(int key,int value)
{
g_content.seg.key=key;
g_content.value=value;
return 0;
}
struct content *get_content()
{
return &g_content;
}
(2)编译成动态库so文件:gcc ctest.c -fPIC -shared -o ctest.so
(3)编写python代码pycall2.py
from ctypes import *
libctest = cdll.LoadLibrary('ctest.so')
class segment_py(Structure):
_fields_=[("key",c_int)]
class content_py(Structure):
_fields_=[("seg",segment_py),
("value",c_int)]
libctest.get_content.restype=POINTER(content_py)
def test():
con=content_py()
libctest.set_kv(1,10)
con=libctest.get_content()
print "key:%s value:%s " % (con.seg.key,con.value)
if __name__ == '__main__'
test()
(4)运行py:$python3 pycall2.py
运行结果略。