0

While wrapping a C++ DLL in Python using ctypes, I'm attempting to pass a 2D np.array of integers to to a wrapped function in the DLL, which is an array of doubles in C++.

Code below:

# create numpy array of int
np_array = np.array([[1503, 0.15],
                     [1504, 0.14],
                     [1505, 0.13],
                     [1506, 0.12]])

# C++ function in DLL wrapped in Python
def fn(double, np_array):

    # import DLL
    my_dll = CDLL('my_dll.dll')

    # create pointer: array of double pointer based on m by n numpy array
    array_of_double_pointer = POINTER(c_double * np_array.shape[1] * np_array.shape[0])

    # convert np.array to ctypes array object:
    c_np_array = np.ctypeslib.as_ctypes(np_array)

    # set argument and return types
    my_dll.fn.argtypes = [c_double, array_of_double_pointer]
    my_dll.fn.restype = c_double

    result = my_dll.fn(double, c_np_array)
    return result

Which throws the error:

OSError: exception: access violation reading 0xFFFFFFFFFFFFFFFF

When print(array_of_double_pointer):

<class '__main__.LP_c_double_Array_2_Array_4'> 

When print(c_np_array):

<__main__.c_double_Array_2_Array_4 object at 0x00000000037B8DC8>

I've also tried the following solution I came across on SO to convert np.array' toctypes' array and create a ctypes array pointer:

c_array= np.ascontiguousarray(np_array, dtype=int)
array_of_double_pointer = c_array.ctypes.data_as(POINTER(c_double))

Which throws the TypeError:

TypeError: item 2 in _argtypes_ has no from_param method
ilbi
  • 51
  • 5
  • which line in your code is throwing the exception? – Dux Jun 04 '18 at 00:37
  • Did you try this? https://stackoverflow.com/questions/8783302/passing-c-double-pointer-to-python – Dmytro Ovdiienko Jun 04 '18 at 01:07
  • @DmytroOvdiienko the `OSERRORL exception: access violation reading 0xFFFFFFFFFFFFFFFF` is thrown by the line `result = my_dll.fn(double, c_np_array)`. – ilbi Jun 04 '18 at 12:32
  • @DmytroOvdiienko yes I did. Also tried to create a _ndarray_ pointer by `array_of_double_pointer = np.ctypeslib.ndpointer(c_double, flags='C_CONTIGUOUS')` and pass in the original _ndarray_ object `np_array` to the function call. This throws the same access violation error. – ilbi Jun 04 '18 at 12:50

0 Answers0