python - 将字符串从 C 返回到 Python

标签 python c python-2.7 shared-libraries

我是 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/

相关文章:

python - Tfidf内存错误: How to avoid this issue?

python - 如何使用 matplotlib 和 seaborn 在绘制的值上显示轴刻度标签?

c - 重新分配结构会导致堆损坏

python-2.7 - Sklearn NotFitted错误: This LinearRegression instance is not fitted yet

python - SciPy 的 interp1d 端点

python - Django Haystack/Elasticsearch dwithin 只返回一个 SearchResult。期待几个

c++ - 二分搜索插入C++中的段错误

c++ - 计算位和位反相中有多少个

python - netcdf创建变量: error an integer is required

python - 加快从网络下载文件的处理速度