0

How can I pass numpy array to c++ double(**) pointer array inside a c++ dll using python ctypes?

My c++ function definition looks like this:

int do_calc(unsigned short** input_array)
{
//doing something with array
}

I tried calling from python in 2 ways:

1.

libhandle = ctypes.CDLL(library_path)
libhandle.do_calc.argtypes = [ctypes.c_void_p]
libhandle.do_calc.restype = ctypes.c_int
//np_array: python numpy array
error_code = libhandle.do_calc(np_array.ctypes.data_as(ctypes.c_void_p))
libhandle = ctypes.CDLL(library_path)
libhandle.do_calc.argtypes = [ctypes.c_void_p]
libhandle.do_calc.restype = ctypes.c_int
//np_array: python numpy array
int_pointer = ctypes.POINTER(ctypes.c_ushort)
error_code = libhandle.do_calc(np_array.ctypes.data_as(int_pointer))

But I am getting this access error in both:

OSError: exception: access violation reading 0x000001C89A480000

1
  • 2
    You can't do that; NumPy arrays are "flat" since that's more efficient. Commented Dec 6, 2022 at 10:09

1 Answer 1

1

As commented, numpy doesn't create double pointers as they are inefficient. Assuming you can alter your C++ definition, this works:

test.cpp

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

extern "C" {

API void do_calc(unsigned short* input_array, size_t rows, size_t cols)
{
    unsigned short x = 0;
    for(size_t r = 0; r < rows; ++r)
        for(size_t c = 0; c < cols; ++c)
            input_array[r * cols + c] = ++x;
}

}

test.py

import numpy as np
import ctypes as ct

dll = ct.CDLL('./test')
# explicitly accept a 2-D numpy array of ushorts
dll.do_calc.argtypes = np.ctypeslib.ndpointer(dtype=ct.c_ushort, ndim=2), ct.c_size_t, ct.c_size_t
dll.do_calc.restype = None

rows, cols = 3, 4
arr = np.zeros((rows, cols), dtype=ct.c_ushort)
dll.do_calc(arr, *arr.shape)
print(arr)

Output:

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.