python - Ctypes:将字符串从 C(++) 传输到 Python

标签 python c++ c string ctypes

我已经为此苦苦挣扎了将近一个星期,也许有人可以帮助我吗?简而言之,我用 C++ 编写了一个程序,并希望将其与 Python 链接(以使用 Flask 或 Django 构建 Web 应用程序)。

我的 C 函数会返回一个 int、char 或 void 工作正常,问题是它们何时应该返回一个字符串。我或多或少明白问题的原因是什么(我的 C 函数返回一个指针,我的 Python 函数无法将其作为有用数据处理)。

这是我编写的示例代码。在我的 main.cpp 文件中,我有以下功能:

extern "C" {
  int addint(int a) {
    return a + 1;
  }

  const char* hello() {
    return "hello";
  }
}

在我的 pywrapper.py 文件中有以下内容:

def addint(number):
    result = lib.addint(c_int(number))
    return result

def saystr():
    result = lib.hello()
    return result

if __name__ == "__main__":
    print('addint: ', addint(5))
    print('saystr: ', saystr())

我的输出是:

addint:  6
saystr:  -354261249

所以第一个函数工作正常。但是对于返回“hello”的第二个函数我能做些什么呢??

最佳答案

作为ctypes documentation shows ,您需要明确告诉它如何处理返回类型:

def saystr():
    lib.hello.restype = c_char_p # pointer to a string
    result = lib.hello()
    return result

否则默认返回类型为int(并且返回的指针被转换为整数地址)。

关于python - Ctypes:将字符串从 C(++) 传输到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41761173/

相关文章:

Python 字典值检查不为空且不为空

python - "TypeError ' xxx' object is not callable"是什么意思?

c++ - 常规初始化中的意外转换

c - 知道在哪里填充了操作结构

c - 当您不知道缓冲区大小时如何避免危险的 vsprintf

c - 在 C 中刷新 linux 串行缓冲区

python - windows 认为 tkinter 没有响应

python - 我可以使用新目标再次加载和训练 Keras 模型吗?

c++ - 取决于枚举的函数重载

c++ - C++ : ScopeGuard vs return check and exception handling?