6

I have the following C code. I am trying to call this function from Python using ctypes:

int add ( int arr []) 
{
 printf("number %d \n",arr[0]);
 arr[0]=1;
 return arr[0];
}

I compiled this by using:

gcc -fpic -c test.c 
gcc -shared -o test.so test.o

then put it in /usr/local/lib.

Python call for this was:

from ctypes import *
lib = 'test.so'
dll = cdll.LoadLibrary(lib)
IntArray5 = c_int * 5
ia = IntArray5(5, 1, 7, 33, 99)
res = dll.add(ia)
print res

but I always get some big number like -1365200.

I tried also:

dll.add.argtypes=POINTER(c_type_int)

but it does not work.

nobody
20.3k17 gold badges59 silver badges80 bronze badges
asked Aug 20, 2014 at 14:23
0

2 Answers 2

5

Instead, try:

dll = cdll.LoadLibrary('test.so')
res = dll.add(pointer(c_int(5)))
print res
answered Aug 20, 2014 at 14:30
Sign up to request clarification or add additional context in comments.

Comments

2

Try to build around that:

lib = 'test.so'
dll = cdll.LoadLibrary(lib)
dll.add.argtypes=[POINTER(c_int)]
# ^^^^^^^^^^^^^^^^
# One argument of type `int *̀
dll.add.restype=c_int
# return type 
res =dll.add((c_int*5)(5,1,7,33,99))
# ^^^^^^^^^
# cast to an array of 5 int
print res

Tested both with Python 2.7.3 and 2.6.9

answered Aug 20, 2014 at 14:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.