gpt4 book ai didi

c++ - 使用 Boost::Python 获取指向 Python 实例的 C++ 指针

转载 作者:太空狗 更新时间:2023-10-29 21:45:14 25 4
gpt4 key购买 nike

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

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

实体.py

class Entity:
def getPointer(self)
return pointertoSelf;

管理器.cpp

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

pointerToPythonObj* = somehowGetPointerToObj("entity");

最佳答案

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


这是一个例子 demonstrating这个:

实体.py:

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

主要.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();
}
}

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

in Entity::action

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

关于c++ - 使用 Boost::Python 获取指向 Python 实例的 C++ 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18041520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com