用ctypes做简单的c调用还是蛮方便的
hello.c
编译动态链接库
$ gcc -o libhello.so -fpic -shared hello.c
返回指针:
>>> import ctypes
>>> hello = ctypes.CDLL("/path/to/libhello.so")
>>> p = hello.foo()
>>> ctypes.c_char_p(p).value
>>> hello world
传入buffer:
>>> b = ctypes.create_string_buffer(12)
>>> hello.foo1(b)
>>> b.value
>>> hello world
hello.c
char *foo(){
char *p = "hello world";
return p;
}
void foo1(char *p){
strcpy(p, "hello world");
}
编译动态链接库
$ gcc -o libhello.so -fpic -shared hello.c
返回指针:
>>> import ctypes
>>> hello = ctypes.CDLL("/path/to/libhello.so")
>>> p = hello.foo()
>>> ctypes.c_char_p(p).value
>>> hello world
传入buffer:
>>> b = ctypes.create_string_buffer(12)
>>> hello.foo1(b)
>>> b.value
>>> hello world
本文介绍如何利用Python的ctypes库来调用C语言编写的动态链接库中的函数。通过两个示例展示了如何从C函数获取字符串返回值及如何向C函数传递缓冲区并修改其内容。
1675

被折叠的 条评论
为什么被折叠?



