Numpy数组到Ctypes数组:访问冲突错误

时间:2018-06-04 00:01:15

标签: python c++ arrays numpy ctypes

在使用ctypes在Python中包装C ++ DLL时,我试图将2D np.array整数传递给DLL中的包装函数,这是一个双精度数组C ++。

以下代码:

# 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

引发错误:

OSError: exception: access violation reading 0xFFFFFFFFFFFFFFFF

print(array_of_double_pointer)时:

<class '__main__.LP_c_double_Array_2_Array_4'> 

print(c_np_array)时:

<__main__.c_double_Array_2_Array_4 object at 0x00000000037B8DC8>

我还尝试了以下我在SO上遇到的解决方案来转换np.array' to ctypes&#39;数组并创建一个ctypes数组指针:

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

抛出TypeError

TypeError: item 2 in _argtypes_ has no from_param method

0 个答案:

没有答案