Pass Strings from Python to C/CPP libs

Python strings are stored in the memory in a way smart but not c-friendly. There are two ways python strings could be stored:

  1. Non-specifically-encoded strings are usually stored as wide chars(wchar), where a string "test" in python basically looks like "t\0e\0s\0t\0". This will mess with any functions in C relying on \0 to find the end of a string(char*).

  2. Encoded string are stored in the specified codec.

Then, to pass a string object as char* or wchar_t* into native libiaries:

  1. import ctypes

  2. Create the prototype of a function via cdll_name.func_name.argtypes=[type,type,type] to specify the types to pass. Use ctypes.c_char_p or ctypes.c_wchar_p to replace the type to specify the type wanted. A full lists of types could be found here under tag 16.16.1.4..

  3. Call the function via cdll_name.func_name(type(arg),type(arg)...). For example: cdll_name.func_name(c_float(3.1),c_char_p("foo"),c_wchar_p("bar"))

2017/10/12