K.G*_*ran 3 c python shared-libraries python-2.7
我对 C 和 Python 都很陌生,我试图将 C 函数getText()引入 Python,但我得到的只是数字
这是foo.c
#include <stdio.h>
const char * getText(void)
{
return "world hello";
}
const char * getText2(void)
{
return "hello world";
}
Run Code Online (Sandbox Code Playgroud)
这是我在终端上的 python 代码
>>> import ctypes
>>> testlib = ctypes.CDLL('/home/user/dir/libfoo.so')
>>> testlib.getText()
743175865
Run Code Online (Sandbox Code Playgroud)
我已经编译了共享对象并puts("Hello world")使用终端中显示的作品对其进行了测试。
我确定我getText()从 python 访问错误,但我不知道是哪一个。任何建议或帮助将不胜感激
ctypes文档中有一个如何处理字符串返回类型的示例。除非外部函数返回 and 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()
Run Code Online (Sandbox Code Playgroud)
输出
世界你好 你好世界