3

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

4
  • Do you with to return a list or to alter a list argument? If you don't know then returning is easier. Commented May 19, 2015 at 15:48
  • You might also wish to consider ctypes in the standard library. Commented May 19, 2015 at 16:08
  • 1
    can you show us your code and sample data you want to pass to python? Commented May 19, 2015 at 16:49
  • I just want to pass the "vector<vector<int> > arr" to python function, in python, it can be tuple or list Commented May 20, 2015 at 2:41

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou tynn, then how to send the value to python scripty after building the tuple. For example, i used this code to send the string: pParam = Py_BuildValue("(s)", "HEHEHE"); pResult = PyEval_CallObject(pFunc,pParam);
0

second loop needs a subtile change from:

for (Py_ssize_t j = 0; i < len; j++)

to

for (Py_ssize_t j = 0; j < len; j++)

with the right running condition statement.

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.