使用 ctypes 将字符串从 python 传递到 c++ - 仅发送第一个字符

passing string from python to c++ using ctypes - only the first character is sent

我正在尝试使用 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 传递过来的。任何建议表示赞赏。

感谢狄龙·戴维斯:

Try ctypes.CDLL(os.path.abspath('nodispersion.so')).nodispersion(b'teststring'). Note the b

这解决了我在传递字符串 'teststring'

的情况下的问题

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

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