I'm having difficulty passing string from Python to C by ctypes:
My C code(compiled into a hello.so)
...
typedef struct test{
unsigned int a;
unsigned char* b;
} my_struct;
int hello(my_struct *in) {
FILE *fp;
...
fprintf(fp, "%d\t%s\n", in->a, in->b);
fclose(fp);
return 0;
}
My Python code:
...
from ctypes import *
...
class TEST_STRUCT(Structure):
_fields_ = [("a", c_int),
("b", c_char_p)]
...
hello_lib = ctypes.cdll.LoadLibrary("hello.so")
hello = hello_lib.hello
hello.argtypes = [POINTER(TEST_STRUCT)]
name = create_string_buffer(b"test")
hello_args = TEST_STRUCT(1, name)
hello(ctypes.byref(hello_args))
...
I get the error: hello_args = TEST_STRUCT(1, name) TypeError: expected string, c_char_Array_5 found
I tried to change c_char_p to c_wchar_p or c_char*5 or c_wchar*5 etc. Sometimes it can run without error, the first int parameter of the struct can be printed correctly, but not the second string pointer, the best I can get is just the first character 't' instead of the whole word "test".
BTW, my python3 version is 3.3.0
name="test"?name = bytes("name", 'utf-8')