Pass C++ object contained in a smart pointer to Python

元气小坏坏 提交于 2019-12-08 02:45:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!