What is the correct pointer type to return from a

2019-08-21 15:47发布

I have a ctypes callback that takes a pointer to two doubles from the dll and returns a pointer to two doubles back to the .dll. The first part works correctly, but after a lot of testing and research, I still can't get the correct pointer to return to the .dll after the callback.

Here's the ctypes callback code:

from scipy.integrate import dblquad
import ctypes

LibraryCB = ctypes.WINFUNCTYPE(ctypes.py_object, ctypes.POINTER(ctypes.c_double))

def LibraryCall(ptr):
    n = ctypes.cast(ptr,ctypes.POINTER(ctypes.c_double))
    x = n[0] #Value = 83.0
    y = n[1] #Value = 30.0
    area = dblquad(lambda x, y: x*y, 0, 0.5, lambda x: 0, lambda x: 1-2*x)
    return_val = area[0], area[1]
    return (return_val)

lib_call = LibraryCB(LibraryCall)

lib_call = ctypes.cast(lib_call,ctypes.POINTER(ctypes.c_longlong))

I used ctypes.py_object as the pointer type to return because all other pointer types return an error that it's not a valid pointer type for a callback.

The pointer returns to the dll, but the values extracted do not match, which suggests that I don't have the correct pointer type.

I also tried casting the return value to a pointer like this: rv = ctypes.cast(return_val,ctypes.POINTER(ctypes.c_double)), and returning that instead, but that didn't work.

Here is the relevant ctypes code that calls the dll and the callback:

CA_data1 = (ctypes.c_double * len(data1))(*data1)
CA_data2 = (ctypes.c_double * len(data2))(*data2)
hDLL = ctypes.WinDLL("C:/NASM_Test_Projects/SciPy_Test/SciPy_Test.dll")
CallName = hDLL.Main_Entry_fn
CallName.argtypes = [ctypes.POINTER(ctypes.c_double),ctypes.POINTER(ctypes.c_double),ctypes.POINTER(ctypes.c_double),ctypes.POINTER(ctypes.c_longlong)]
CallName.restype = ctypes.c_double

ret_ptr = CallName(CA_data1,CA_data2,length_array_out,lib_call)

Thanks very much for any ideas on how to solve this.

1条回答
等我变得足够好
2楼-- · 2019-08-21 16:23

The DLL code would have to deal directly with Python objects. You can't simply cast a Python object to a ctypes pointer. The easiest way to do what you want if you can change the DLL code is to use an input/output parameter:

test.c

#include <stdio.h>

typedef void (*CALLBACK)(double*);

__declspec(dllexport) void function(CALLBACK callback)
{
    double param[2] = {1.5, 2.5};
    callback(param);
    printf("%lf %lf\n",param[0],param[1]);
}

test.py

from ctypes import *

CALLBACK = PYFUNCTYPE(None,POINTER(c_double))

@CALLBACK
def LibraryCB(data):
    x = data[0]
    y = data[1]
    print(x,y)
    data[0] *= 2
    data[1] *= 2

dll = CDLL('test')
dll.function.argtypes = [CALLBACK]
dll.function.restype = None

cb = CALLBACK(LibraryCB)

dll.function(cb)

Output

1.5 2.5
3.000000 5.000000
查看更多
登录 后发表回答