问题
I have a class in C++.
I create an object from this class in my C++ code. I want this object to be accessible in Python. I use boost::shared_ptr
to keep the object address.
I've checked out some posts about this but wasn't very helpful. I think the best way is to make an object in Python namespace after interpreter initialization and then assign my boost shared_ptr to the created object in Python.
I've wrapped my class using BOOST_PYTHON_MODULE
in cpp and tested some ways like namespace["my_module_name_in_python"] = class<"my_class">...
to be able to create an object in python and fill it with the shared_ptr
.
In summery my question is how's possible to pass a C++ object contained in a shared_ptr
to python.
Thanks in advance
回答1:
This is taken from the official boost python documentation.
Lets say you have a C++ class that looks like this:
class Vec2 {
public:
Vec2(double, double);
double length();
double angle();
};
You can derive the Python interface for it like that:
object py_vec2 = class_<Vec2>("Vec2", init<double, double>())
.def_readonly("length", &Point::length)
.def_readonly("angle", &Point::angle)
)
The class definition is now stored in the variable py_vec2
. Now I can create an instance of said class with:
object vec_instance = py_vec2(3.0, 4.0);
This instance can now be injected to a Python interpreter. E.g set it into a variable of the "__main__"
module:
object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
main_namespace["vec_instance"] = vec_instance;
来源:https://stackoverflow.com/questions/18873885/pass-c-object-contained-in-a-smart-pointer-to-python