【问题标题】:Get a c++ pointer to a Python instance using Boost::Python使用 Boost::Python 获取指向 Python 实例的 c++ 指针
【发布时间】:2013-08-05 04:16:00
【问题描述】:

我正在将 Python 嵌入到 C++ 应用程序中。当我在 Python 中创建一个新对象时,我希望能够在我的 C++ 应用程序中存储对该对象的引用,以便以后可以调用该对象上的方法。这样做的推荐方法是什么?

例如,我希望能够做这样的事情:

Entity.py

class Entity:
    def getPointer(self)
        return pointertoSelf;

Manager.cpp

Py_Initialize();
PyRun_SimpleString("import Entity");
PyRun_SimpleString("entity = Entity.Entity()");

pointerToPythonObj* = somehowGetPointerToObj("entity");

【问题讨论】:

    标签: c++ python boost scripting boost-python


    【解决方案1】:

    推荐的方法是查询创建entity 对象的命名空间,然后将entity 对象的句柄存储为boost::python::object。从 C++ 与 Python 对象交互时,最好尽可能使用boost::python::object,因为它提供了一种类似于 Python 变量的高级表示法。此外,它还提供适当的引用计数来管理 Python 对象的生命周期。例如,存储原始指针(即 pointerToPythonObj* )不会延长 Python 对象的生命周期;如果 Python 对象是从解释器内部进行垃圾回收的,那么 pointerToPythonObj 将是一个悬空指针。


    这是一个例子demonstrating这个:

    Entity.py:

    class Entity:
        def action(self):
            print "in Entity::action"
    

    main.cpp:

    #include <boost/python.hpp>
    
    int main()
    {
      namespace python = boost::python;
      try
      {
        Py_Initialize(); // Start interpreter.
    
        // Create the __main__ module.
        python::object main = python::import("__main__");
        python::object main_namespace = main.attr("__dict__");
    
        // Import Entity.py, and instantiate an Entity object in the
        // global namespace.  PyRun_SimpleString could also be used,
        // as it will default to running within and creating 
        // __main__'s namespace.
        exec(
            "import Entity\n"
            "entity = Entity.Entity()\n"
          , main_namespace
        );
    
        // Obtain a handle to the entity object created from the previous
        // exec.
        python::object entity = main_namespace["entity"];
        // Invoke the action method on the entity.
        entity.attr("action")();
      }
      catch (const python::error_already_set&)
      {
        PyErr_Print();
      }
    }
    

    运行上述程序会产生以下输出:

    在 Entity::action 中

    如果Entity.py 无法导入,则可能需要将其包含目录添加到PYTHONPATH 环境变量中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-29
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多