2017-04-10 5 views
2

I définir une fonction dans la bibliothèque C comme suit:ctypes.ArgumentError: Je ne sais pas comment convertir le paramètre

int* Test(char *str1,int id1,char *str2,float val,float *ls) 

Je veux l'utiliser en python donc j'écrire le code python suivant:

str1 = 'a' 
str2 = 'b' 
id1 = 0 
val = 1.0 
system('g++ -c -fPIC libtraj.cpp -o test.o') 
system('g++ -shared -Wl,-soname,test.so -o test.so test.o') 
lib = cdll.LoadLibrary('./test.so') 
num_item = 100000 
ls = (ctypes.c_float * num_item)() 
lib.Test.restype = ndpointer(dtype=ctypes.c_int, shape=(num_item,)) 
lib.Test.argtypes = [c_char_p] 
a = create_string_buffer(str1) 
b = create_string_buffer(str2) 
ls_id = lib.Test(a,id1,b,val,ctypes.byref(ls)) 

Ensuite, je lance ce programme python. J'ai rencontré une erreur en disant:

ls_id = lib.Test(a,id1,b,val,ctypes.byref(ls)) 
ctypes.ArgumentError: argument 4: <type 'exceptions.TypeError'>: Don't know how to convert parameter 4 

Quel est le problème avec mon code? Merci à tous pour m'avoir aidé !!!

+0

vous ne voulez pas utiliser SWIG (http://www.swig.org/tutorial.html)? –

+3

Essayez: 'lib.Test.argtypes = [c_char_p, c_int, c_char_p, c_float, POINTER (c_float)]' (tous définis par 'ctypes'). – CristiFati

+0

Aussi 'ndpointer' semble être lié à _numpy _.... si c'est le cas, il y a de grandes chances pour que le mélange avec _ctypes_ ne fonctionne pas. – CristiFati

Répondre

1

La solution fournie par @CristiFati résout mon problème. Je copie juste sa réponse dans les commentaires et présente ici. Merci @CristiFati.

Essayez:

lib.Test.argtypes = [c_char_p, c_int, c_char_p, c_float, POINTER(c_float)] (all defined by ctypes)