【发布时间】:2018-07-04 17:02:11
【问题描述】:
我有一个小的 Python 程序需要从我的 C 共享库中调用一个函数:
C程序优先:
#include <stdio.h>
#include <stdlib.h>
void myprint(const char*, char**);
void myprint(const char* input, char** output)
{
printf("hello world\n");
printf("input string: %s\n",input);
*output = (char*) malloc(20);
sprintf(*output,"Life is cheap\n");
printf("output string in C program: %s\n",*output);
}
编译成共享库:
gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c
您会注意到该函数需要一个 char 指向指针的指针作为它的第二个参数。它将填充这个参数,我希望调用它的 python 程序能够打印它。
我试图通过将引用传递给一个指针来从调用者 python 程序中实现这一点:
import ctypes
mem = POINTER( c_ubyte )()
testlib = ctypes.CDLL('/home/amanral/testlib.so')
testlib.myprint("hell with the world",byref(mem))
#print mem ===> This is where I want to print back the value filled by the C function
我知道 print mem 是错误的,因为它只是打印:
<__main__.LP_c_ubyte object at 0x7f6460246560>
是否甚至可以打印回存储在内存中的实际字符串? 有没有更好的解决方案?
【问题讨论】:
-
对不起,如果这是题外话,但在 C 空间中分配内存似乎有泄漏。那段内存怎么释放? C和python分配内存的方式一样吗?
-
@billjamesdev - 你是对的。到目前为止,这是泄漏的。理想情况下,我想在 python 中分配内存并将其传递给 C 库函数。这可能吗?
-
@billjamesdev - 请参阅下面的答案。现在在 Python 程序中分配了缓冲内存,并将指针传递给 C 函数。希望这看起来更好吗?
标签: python c shared-libraries ctypes