2017-04-10 38 views
2

轉換我在C中定義庫中的函數如下:ctypes.ArgumentError:不知道如何參數

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

我想在Python中使用它,所以我寫了下面的Python代碼:

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)) 

然後我運行這個python程序。我遇到錯誤說:

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 

我的代碼有什麼問題? 謝謝大家的幫助!

+0

(http://www.swig.org/tutorial.html)? –

+3

嘗試:'lib.Test.argtypes = [c_char_p,c_int,c_char_p,c_float,POINTER(c_float)]'(全部由'ctypes'定義)。 – CristiFati

+0

另外'ndpointer'似乎與_numpy _有關,如果是的話,那麼將它與_ctypes_混合的機會將不起作用。 – CristiFati

回答

1

@CristiFati提供的解決方案解決了我的問題。我只是在評論中複製他的答案,並在這裏呈現。謝謝@CristiFati。

嘗試:

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

你不想使用痛飲