Sto avendo difficoltà di minzione stringa da Python a C da ctypes:Problema con il passare stringa da Python a C condiviso lib utilizzando ctypes
Il mio codice C (compilato in un 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;
}
codice
mio Python:
...
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))
...
ottengo l'errore: hello_args = TEST_STRUCT (1, nome) TypeError: atteso stringa, c_char_Array_5 trovato
Ho provato a cambiare c_char_p in c_wchar_p o c_char * 5 o c_wchar * 5 ecc. A volte può funzionare senza errori, il primo parametro int della struct può essere stampato correttamente, ma non il secondo puntatore di stringa, il migliore I può ottenere è solo il primo carattere 't' al posto dell'intera parola "test".
BTW, la mia versione python3 è 3.3.0
Non so nulla sull'invio di dati tra C e Python, ma cosa succede quando assegni il nome come 'name =" test "'? –
Se faccio Python come questo: hello_lib = ctypes.cdll.LoadLibrary ("hello.so") ciao = hello_lib.hello hello.argtypes = [POINTER (TEST_STRUCT)] #name = create_string_buffer (b "di prova ") name = "test" hello_args = TEST_STRUCT (1, nome) ciao (ctypes.byref (hello_args)) ottengo: TypeError: byte o indirizzo intero attesi anziché esempio str – Alex
Chissà se che si riferisce a un oggetto byte 'nome = byte (" nome "," utf-8 ")' –