Reputation: 53
I'm trying to execute my Python Code that must call a C function, which execute some calculation and save the value in a pointer that must be accessible from Python code. I'd like to do that because i'm constructing a DLL and i want to validate the algebra inside the DLL function, therefore i'd like to use a python code to validate the DLL. The Python Code
from ctypes import *
if __name__ == '__main__':
mydll = cdll.LoadLibrary("./dll_simples.dll")
funcao = mydll.simuser
funcao.argtypes = c_double,c_double,POINTER(c_double),POINTER(c_double)
a = 0
b = 0
input_1 = (c_double * 1)()
input_1[0] = 5
output_1 = (c_double * 1)()
funcao(a,b,input_1,output_1)
and my DLL
__declspec(dllexport) void simuser(double t, double delt, double* in, double* out)
{
out[0] = 2 * in[0];
}
after executing this code, i have the error
funcao(a,b,input_1,output_1)
OSError: exception: access violation reading 0x0000000000000018
Upvotes: 2
Views: 337
Reputation: 41167
Listing [Python 3.Docs]: ctypes - A foreign function library for Python.
So, you want to pass an array to a function that expects a pointer. For that case, ctypes.cast is required:
So, instead of:
funcao(a, b, input_1, output_1)
use:
funcao(a, b, cast(input_1, POINTER(c_double)), cast(output_1, POINTER(c_double)))
Looking at the existing C code, it only uses one value for the 2 pointers, case in which you won't be needing arrays at all (but I doubt that's the intent because then the input value shouldn't be a pointer):
# ...
input_1 = c_double(5)
output_1 = c_double(0)
funcao(a, b, byref(input_1), byref(output_1))
A working example: [SO]: Pointer from Python (ctypes) to C to save function output (@CristiFati's answer).
Upvotes: 1