将智能指针中包含的C ++对象传递给Python [英] Pass C++ object contained in a smart pointer to Python

查看:178
本文介绍了将智能指针中包含的C ++对象传递给Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中有一个类.
我在C ++代码中从此类创建一个对象.我希望可以在Python中访问此对象.我使用boost::shared_ptr保留对象地址.

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.

我已经检查了一些有关此的帖子,但不是很有帮助. 我认为最好的方法是在解释器初始化后在Python名称空间中创建一个对象,然后将我的boost shared_ptr分配给在Python中创建的对象.

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.

我已经在cpp中使用BOOST_PYTHON_MODULE封装了我的课程,并测试了namespace["my_module_name_in_python"] = class<"my_class">...之类的方法,以便能够在python中创建对象并用shared_ptr填充它.

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.

在夏季,我的问题是如何将shared_ptr中包含的C ++对象传递给python.

In summery my question is how's possible to pass a C++ object contained in a shared_ptr to python.

预先感谢

推荐答案

这取自官方的boost python文档.

This is taken from the official boost python documentation.

假设您有一个C ++类,如下所示:

Lets say you have a C++ class that looks like this:

class Vec2 {
public:
    Vec2(double, double);
    double length();
    double angle();
};

您可以像这样派生Python接口:

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)
)

类定义现在存储在变量py_vec2中.现在,我可以使用以下方法创建所述类的实例:

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);

现在可以将该实例注入到Python解释器中.例如,将其设置为"__main__"模块的变量:

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;

这篇关于将智能指针中包含的C ++对象传递给Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆