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?
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With