Converting python string object to c char* using ctypes Converting python string object to c char* using ctypes python-3.x python-3.x

Converting python string object to c char* using ctypes


Thanks to Eryksun the solution:

Python code

string1 = "my string 1"string2 = "my string 2"# create byte objects from the stringsb_string1 = string1.encode('utf-8')b_string2 = string2.encode('utf-8')# send strings to c functionmy_c_function.argtypes = [ctypes.c_char_p, ctypes.char_p]my_c_function(b_string1, b_string2)


I think you just need to use c_char_p() instead of create_string_buffer().

string1 = "my string 1"string2 = "my string 2"# create byte objects from the stringsb_string1 = string1.encode('utf-8')b_string2 = string2.encode('utf-8')# send strings to c functionmy_c_function(ctypes.c_char_p(b_string1),              ctypes.c_char_p(b_string2))

If you need mutable strings then use create_string_buffer() and cast those to c_char_p using ctypes.cast().


Have you considered using SWIG? I haven't tried it myself but here's what it would look like, without changing your C source:

/*mymodule.i*/%module mymoduleextern void my_c_function(const char* str1, const char* str2);

This would make your Python source as simple as (skipping compilation):

import mymodulestring1 = "my string 1"string2 = "my string 2"my_c_function(string1, string2)

Note I'm not certain .encode('utf-8') is necessary if your source file is already UTF-8.