10

I define a function in C library as follows:

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

I want to use it in python so I write the following python code:

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

Then I run this python program. I met with error saying:

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

What's wrong with my code? Thank you all for helping me!!!

rkersh
  • 4,447
  • 2
  • 22
  • 31
pfc
  • 1,831
  • 4
  • 27
  • 50
  • 5
    Try: `lib.Test.argtypes = [c_char_p, c_int, c_char_p, c_float, POINTER(c_float)]` (all defined by `ctypes`). – CristiFati Apr 10 '17 at 11:08
  • Also `ndpointer` seems to be related to _numpy_....if so, there's a great chance that mixing it with _ctypes_ won't work. – CristiFati Apr 10 '17 at 15:58

1 Answers1

9

The solution provided by @CristiFati solves my problem. I just copy his answer in the comments and present here. Thank you @CristiFati.

Try:

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

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
pfc
  • 1,831
  • 4
  • 27
  • 50