Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass Two-dimensional array from C to Python

Tags:

c++

python

c

I want to pass the two-dimensional array to python from C.

How can I use the Py_BuildValue() and PyEval_CallObject()?

For example, i can use the following code to pass string from C to python:

pModule = PyImport_ImportModule("python_code");
pFunc = PyObject_GetAttrString(pModule, "main");
pParam = Py_BuildValue("(s)", "HEHEHE");
pResult = PyEval_CallObject(pFunc,pParam);

Now, i want to pass the two-dimensional array and a string to python

like image 740
vinllen Avatar asked Feb 12 '26 02:02

vinllen


1 Answers

So basically, you want to build a tuple, not parse one.

This is just a straightforward example of how you could convert your arr to a tuple of tuples. Here you should add some error checking at some point in time as well.

Py_ssize_t len = arr.size();
PyObject *result = PyTuple_New(len);
for (Py_ssize_t i = 0; i < len; i++) {
    Py_ssize_t len = arr[i].size();
    PyObject *item = PyTuple_New(len);
    for (Py_ssize_t j = 0; j < len; j++)
        PyTuple_SET_ITEM(item, j, PyInt_FromLong(arr[i][j]));
    PyTuple_SET_ITEM(result, i, item);
}

(For Python 3 C API, replace PyInt_FromLong(arr[i][j]) with PyLong_FromLong(arr[i][j]))

Then you can build your args, like you did with the string. Instead of s for string, you would use O for PyObject * (or N if you don't want to increment the reference count):

pParam = Py_BuildValue("(O)", result);

Maybe boost::python could provide a simpler method, but I don't realy know the library myself.

like image 56
tynn Avatar answered Feb 14 '26 14:02

tynn