您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Boost-python如何将C ++类实例传递给python类

Boost-python如何将C ++类实例传递给python类

通过boost :: python :: ptr将对象指针传递给python。这将阻止python解释器进行复制:

#include <boost/python.hpp>
#include <string>
#include <iostream>

using namespace boost::python;
using namespace std;

class World
{
private:
    string name;
public:
    void set(string name) {
        this->name = name;
    }
    void greet() {
        cout << "hello, I am " << name << endl;
    }
};

typedef boost::shared_ptr< World > world_ptr;

BOOST_PYTHON_MODULE(hello)
{
    class_<World>("World")
        .def("greet", &World::greet)
        .def("set", &World::set)
    ;
};

int main(int argc, char **argv)
{
    Py_Initialize();
    try {
        PyRun_SimpleString(
            "class Person:\n"
            "    def sayHi(self):\n"
            "        print 'hello from python'\n"
            "    def greetReset(self, instance):\n"
            "        instance.set('Python')\n"
          );

        world_ptr worldObjectPtr (new World);
        worldObjectPtr->set("C++!");

        inithello();
        object o_main 
            = object(handle<>(borrowed(PyImport_AddModule("__main__"))));
        object o_person_type = o_main.attr("Person");
        object o_person = o_person_type();
        object o_func1 = o_person.attr("sayHi");
        o_func1();
        object o_func2 = o_person.attr("greetReset");
        o_func2(boost::python::ptr(worldObjectPtr.get()));
        worldObjectPtr->greet();
    }
    catch (error_already_set) {
        PyErr_Print();
    }

    Py_Finalize();

    return 0;
}
python 2022/1/1 18:30:31 有417人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶