我已经很多年没有使用 C 了,所以我一直在研究如何从一个简单的库中取回字符串并将其导入 Python。
测试.c
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * get_string() {
char theString[]= "This is my test string!";
char *myString = malloc ( sizeof(char) * (strlen(theString)) +1 );
strcpy(myString, theString);
return myString;
}
我使用以下代码编译代码:
gcc -Wall -O3 -shared test.c -o test.so
python.py
#!/usr/bin/env python
import ctypes
def main():
string_lib = ctypes.cdll.LoadLibrary('test.so')
myString = string_lib.get_string()
print ctypes.c_char_p(myString).value
if __name__ == '__main__':
main()
当我运行 Python 脚本时,我得到:
Segmentation fault: 11
如果我只打印结果,我会得到一个数值,我假设它是指针...我怎样才能让它工作?
谢谢!
最佳答案
问题是您使用的是 64 位 Python。这将截断返回的指针。
先声明restype:
import ctypes
def main():
string_lib = ctypes.cdll.LoadLibrary('test.so')
string_lib.get_string.restype = ctypes.c_char_p
myString = string_lib.get_string()
print myString
if __name__ == '__main__':
main()
关于Python,从C库中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30287132/