简体   繁体   English

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

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

I am trying to send a multi-character string from Python to C++ using ctypes. 我正在尝试使用ctypes将多字符字符串从Python发送到C ++。 However only the first character of each string is passed. 但是,仅传递每个字符串的第一个字符。

This is the call in Python: 这是Python中的调用:

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

And how I define in C++: 以及我在C ++中的定义方式:

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

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

Results in only 't' being printed. 结果仅打印“ t”。

Other types such as int pass fine. 其他类型(例如int)可以很好地通过。 In addition if I define the char* in c++ it prints fine so I assume it's something in when it gets passed from Python. 另外,如果我在c ++中定义char *,它可以很好地打印,因此我认为它是从Python传递过来的东西。 Any advice appreciated. 任何建议表示赞赏。

Thanks Dillon Davis: 感谢狄龙·戴维斯(Dillon Davis):

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

This solved my problem in the case of passing the string 'teststring' 这在传递字符串'teststring'的情况下解决了我的问题

However I then wanted to pass a string that had been previously defined in Python as a variable. 但是,然后我想传递一个以前在Python中定义为变量的字符串。 This was solved by using bytes function and defining encoding as 'utf8': 这是通过使用bytes函数并将编码定义为“ utf8”解决的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM