【问题标题】:passing string from python to c++ using ctypes - only the first character is sent使用 ctypes 将字符串从 python 传递到 c++ - 只发送第一个字符
【发布时间】:2019-07-28 23:08:16
【问题描述】:

我正在尝试使用 ctypes 将多字符字符串从 Python 发送到 C++。但是只传递了每个字符串的第一个字符。

这是 Python 中的调用:

ctypes.cdll.LoadLibrary(os.path.abspath("nodispersion.so"))
ctypes.CDLL(os.path.abspath('nodispersion.so')).nodispersion('teststring')

以及我如何在 C++ 中定义:

extern "C" void nodispersion(char* test)
{

    cout << "print test " << test << "\n";
}

只打印“t”。

其他类型如 int 也可以通过。此外,如果我在 c++ 中定义 char* ,它的打印效果很好,所以我认为它是从 Python 传递过来的。任何建议表示赞赏。

【问题讨论】:

  • 试试ctypes.CDLL(os.path.abspath('nodispersion.so')).nodispersion(b'teststring')。注意b
  • 您希望通过哪种方式修改传递的字符串?如果您不这样做,请将其设为const。这可能有助于 Python 找出应该以何种方式传递参数。此外,如果您想用 C++ 编写 Python 模块,现有的框架可以使集成变得更加容易。恕我直言,cdll 方法适用于您无法访问源代码或原型设计的情况。

标签: python c++ char ctypes


【解决方案1】:

感谢狄龙戴维斯:

试试 ctypes.CDLL(os.path.abspath('nodispersion.so')).nodispersion(b'teststring')。注意 b

这解决了我在传递字符串'teststring'的情况下的问题

但是,我想将之前在 Python 中定义的字符串作为变量传递。这是通过使用bytes 函数并将编码定义为'utf8'来解决的:

a = 'teststring'
ctypes.CDLL(os.path.abspath('nodispersion.so')).nodispersion(bytes(a, encoding='utf8'))

【讨论】:

    猜你喜欢
    • 2021-04-27
    • 2017-06-05
    • 2020-08-01
    • 2021-11-02
    • 2017-04-21
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多