Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass an array to shared library(.dll) written in c using python

the function code of test.dll file:

double __cdecl add(int len,double array[]){}

(and I have tested it in vc)

python code:

import ctypes
from ctypes import *

N=...
arr=(c_double*N)()
...
...
dll=CDLL("test.dll")
sum=dll.add(c_int(N),byref(arr))

print sum

but the python code doesn't work, and the "sum"is always equal to N .(i.g. when N=10 ,it print"sum=10") what's wrong with it?

like image 641
lyx Avatar asked Mar 26 '12 14:03

lyx


People also ask

How do I pass an array from C to Python?

Cast the pointer to the array to intptr_t , or to explicit ctypes type, or just leave it un-cast; then use ctypes on the Python side to access it. Cast the pointer to the array to const char * and pass it as a str (or, in Py3, bytes ), and use struct or ctypes on the Python side to access it.

Can Python use DLL files?

New in Python version 2.5 is the ctypes, a foreign function library. It provides C-compatible data types and allows calling functions in DLLs or shared libraries. Using the ctypes module in Python allows ArcObjects code written in C++ to be used in a geoprocessing script tool.


1 Answers

Passing an array in ctypes mirrors passing an array in C, i.e. you do not need to pass a reference to it as the array is already a reference to its first element.

from ctypes import *

N = ...
arr=(c_double*N)()
dll=CDLL("test.dll")
sum=dll.add(c_int(N),arr)

print sum

An example of this can be seen in the ctypes documentation under the callbacks section when discussing interfacing with qsort.

Edit: As per David Heffernan's comment, you also require a dll.add.restype = c_double otherwise ctypes will assume the returned type is c_int.

like image 136
Iain Rist Avatar answered Sep 29 '22 06:09

Iain Rist