简体   繁体   中英

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. However only the first character of each string is passed.

This is the call in Python:

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

And how I define in C++:

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

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

Results in only 't' being printed.

Other types such as int pass fine. 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. Any advice appreciated.

Thanks Dillon Davis:

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

This solved my problem in the case of passing the string 'teststring'

However I then wanted to pass a string that had been previously defined in Python as a variable. This was solved by using bytes function and defining encoding as 'utf8':

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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