Skip to content
Advertisement

How to make c++ return 2d array to python

I find an example showing how to return a 1D array from c++ to python. Now I hope to return a 2D array from c++ to python. I imitate the code shown in the example and my code is as follows:

The file a.cpp:

JavaScript

The file b.py:

JavaScript

I run the following commands:

JavaScript

Then I get the following prints:

JavaScript

It seems I succeed in returning 1D array, just in the same way shown in the example. But I fail in returning 2D array. How can I get it work? Thank you all for helping me!!!

Advertisement

Answer

You are allocating your array incorrectly.

int* may point to a beginning of a 1D attay.

int** never points to a beginning of a 2D array. It may point to a beginning of 1D array of pointers, each of which in turn point to a beginning of a 1D array. This is a legitimate data structure, but it’s different from a 2D array and is not compatible with Python’s

JavaScript

To return a real 2D array, you can do this:

JavaScript

Note that in a 2D array in C++ all dimensions except one are fixed.

If you want to return something that Python can interpret as a 2D array, you can return a 1D array:

JavaScript

Python will use it as a 3×3 matrix just fine. This allows you to vary all array dimensions: C++ never knows it’s a 2D array, you just multiply all the dimensions together.

If you for some reason do need an array of pointers (not recommended), you need to use something like this on the Python side:

JavaScript

(I’m not a ctypes guru so take this with the grain of salt).

Finally, consider using boost::python. With it you can use std::vector on the C++ side normally, without resorting to low level hackery.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement