从C返回字符串到Python

吉布兰

我是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")终端中显示的工程对其进行了测试

我确定我是getText()从python错误访问的,但是我不知道是哪一个。任何建议或帮助,将不胜感激

姆霍克

ctypes文档中有一个如何处理字符串返回类型的示例除非外部函数返回和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()

输出

世界你好
你好世界

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章