Reputation: 449
I got a Python list which I can obtain its pointer and pass this pointer address to C++ to work on
MyPointer = TheList.as_pointer()
now I pass this address to C++ with ctypes
in C++ I can do the following:
*(float*) MyPointer = 2.0f; //for example
and the Python values will update immediatly,now the problem is:
how to extend or delete some values (like modify the list directly from C++)
as I sense these data are a std::vector
how to do push_back
and so on to adjust size with a fast way (as iterating in Python is pretty much SLOW)
Upvotes: 4
Views: 1327
Reputation: 154926
Given only that pointer, you cannot extend the list. What you are passing to C++ is the address of the array internally used to implement the Python list. This cannot be an std::vector
, as Python lists are not implemented as STL vectors, but as C-level arrays of Python object references. These arrays do not contain a backpointer to the Python list object.
To mutate the list, take a look at the documentation and link your C++ code with the Python library. If you really must call your C++ function from ctypes, call it with the id
of the list to get the pointer to the list, as opposed to its element array. Then you can operate on the list like this:
#include <Python.h>
extern "C"
void append_to_list(uintptr_t lst_id)
{
PyObject* lst = reinterpret_cast<PyObject*>(ptr);
PyObject* new_num = PyFloat_FromDouble(2.0);
if (!new_num) {
... PyFloat creation failed ...
}
int ret = PyList_Append(lst, new_num);
Py_DECREF(new_num);
if (ret) {
... PyList_Append failed ...
}
}
Upvotes: 6