我是 C 和 Python 的新手,我正在尝试将 C 函数 getText()
导入 Python,但我得到的只是数字
这是foo.c
#include <stdio.h>
const char * getText(void)
{
return "world hello";
}
const char * getText2(void)
{
return "hello world";
}
这是我来自终端的 python 代码
>>> import ctypes
>>> testlib = ctypes.CDLL('/home/user/dir/libfoo.so')
>>> testlib.getText()
743175865
我已经编译了共享对象并使用 puts("Hello world")
对其进行了测试,因为它出现在终端中。
我确定我从 python 错误地访问了 getText()
但我不知道是哪一个。任何建议或帮助将不胜感激
最佳答案
ctypes
documentation 中有一个如何处理字符串返回类型的示例.除非外部函数返回int
,否则您需要使用.restype
属性设置外部函数的返回类型。对于您的代码:
import ctypes
testlib = ctypes.CDLL('/home/user/dir/libfoo.so')
testlib.getText.restype = testlib.getText2.restype = ctypes.c_char_p
print testlib.getText()
print testlib.getText2()
输出
world hello hello world
关于python - 将字符串从 C 返回到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34035643/