Question

First off I am new to ctypes and did search for an answer to my question. Definitely will appreciate any insight from here.

I have a byte string supplied to me by another tool. It contains what appears to be hex and other values. I'm creating the c_char_p object as follows:

mybytestring = b'something with a lot of hex \x00\x00\xc7\x87\x9bb and other alphanumeric and non-word characters'     # Length of this is very long let's say 480
mycharp = c_char_p(mybytestring)

I also create a c_char_Array as follows:

mybuff = create_string_buffer(mybytestring)

The problem is when I send either mycharp or mybuff to a c++ library .so function, the string gets cut off at the NULL terminator (first occurrence of '\x00')

I'm loading the c++ library and calling the function as follows:

lib_handle = cdll.LoadLibrary(mylib.so)
lib_handle.myfunction(mycharp)
lib_handle.myfunction(mybuff)

The c++ function expects a char *

Does someone know how to be able to send the whole string with NULL terminators ('\x00') included?

Thanks

Was it helpful?

Solution

Add your original data to a vector<char> vec, and send vec.data()

But the actual problem is

The c++ function expects a char *.

You will need to change this (to accept a second arg=length of the buffer, or for example, to accept a vector<char>) if you want it to accept an array of char including null.

Alternatively you can figure out what do you actually want the c++ function to do, and make self a "preprocessing" of the char array, adding a null-terminator to each new array, and after that send to the c++ function.

For example, you may decide that the “input” array is actually a set of c-string: you will need to do a simple parse to “split” and send to the c++ in a cycle one, after other.

Or maybe you decide that the input could be a string in an UTF16 and not UTF8. Then you need to, as good as possible, convert it to UTF8 and send to the c++ function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top