Sujeet Kalaskar Sujeet Kalaskar - 2 months ago 14
C++ Question

C++ to communicate to Python function

I am new to c++,

I created DLL which contains Class, and functions and all the return type of each function is PyObject (Python Object), So now i want to write the C++ application which loads DLL dynamically using LoadLibrary function.

Able to execute with adding the project to same solution and adding the reference to DLL.

I am able to load the DLL, but when i am calling the function it returns PyObject data type, how to store the return type of PyObject in C++?

Answer

You should take a look at Python's documentation on Concrete Objects Layer. Basically you have to convert PyObject into a C++ type using a function of the form Py*T*_As*T*(PyObject* obj) where T is the concrete type you want to retrieve. Here is an example to convert a PyObject into long:

PyObject* some_py_object = /* ... */;

long as_long(
    PyLong_AsLong(some_py_object)
);

Py_DECREF(some_py_object);

The API assumes you know which function you should call.

Here is another, more complicated example converting a Python list into a std::vector:

PyObject* some_py_list = /* ... */;

// assuming the list contains long

std::vector<long> as_vector(PyList_Size(some_py_list));

for(size_t i = 0; i < as_vector.size(); ++i)
{
    PyObject* item = PyList_GetItem(some_py_list, i);

    as_vector[i] = PyLong_AsLong(item);

    Py_DECREF(item);
}

Py_DECREF(some_py_list);

A last, more complicated example, to parse a Python dict into a std::map:

PyObject* some_py_dict = /* ... */;

// assuming the dict uses long as keys, and contains string as values

std::map<long, std::string> as_map;

// first get the keys
PyObject* keys = PyDict_Keys(some_py_dict);

size_t key_count = PyList_Size(keys);

// loop on the keys and get the values
for(size_t i = 0; i < key_count; ++i)
{
    PyObject* key = PyList_GetItem(keys, i);
    PyObject* item = PyDict_GetItem(some_py_dict, key);

    // add to the map
    as_map.emplace(PyLong_AsLong(key), PyString_AsString(item));

    Py_DECREF(key);
    Py_DECREF(item);
}

Py_DECREF(keys);
Py_DECREF(some_py_dict);