I'm writing a library for python in C++ using boost::python and I've hit a snag.
I'd like to take an object (in this case, an np.array) and run some python code on it (in this case, the code that gets the data pointer from an array). The problem is that the boost tutorial doesn't specifically say how to get a python object that is in the C++ code and pass it to the python code you want to run.
Here is a sketch of what I want to do:
#include <boost/python.hpp>
#include <cctypes>
void* get_data_ptr(boost::python::object& array) {
boost::python::object main_module = import("__main__");
boost::python::object main_namespace = main_module.attr("__dict__");
boost::python::object ignored = exec(
"import ctypes\n"
"temp = ctypes.c_void_p.from_buffer(array)\n"
"py_ptr = ctypes.addressof(temp)\n",
main_namespace); // array would have to go to python somehow
uintptr_t ptr = extract<uintptr_t>(main_namespace["py_ptr"]);
// Some operation on the np array
}
How would I do that?
PS: It is important that my method does not have collateral effects, I.E. does not add anything such as a variable to the global namespace that would alter the python code that is running on top of it.
Copyright Notice:Content Author:「Jean-Luc Nacif Coelho」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/45090595/running-python-code-in-a-python-object-in-boostpython