![](/img/trans.png)
[英]Call a C++ function that takes pointer to an array using boost::python
[英]Get a c++ pointer to a Python instance using Boost::Python
我正在努力將Python嵌入到C ++應用程序中。 當我在Python中創建一個新對象時,我希望能夠在我的C ++應用程序中存儲對該Object的引用,以便稍后可以調用該對象上的方法。 建議的方法是什么?
例如,我希望能夠做到這樣的事情:
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");
建議的方法是查詢創建entity
對象的命名空間,然后將entity
對象的句柄存儲為boost::python::object
。 當與C ++中的Python對象進行交互時,最好盡可能使用boost::python::object
,因為它提供了一個與Python變量非常相似的高級表示法。 此外,它還提供適當的引用計數來管理Python對象的生命周期。 例如,存儲原始指針(即pointerToPythonObj*
)不會延長Python對象的生命周期; 如果Python對象是從解釋器中收集的垃圾,那么pointerToPythonObj
將是一個懸空指針。
這是一個證明這一點的例子:
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();
}
}
運行以上程序會產生以下輸出:
in Entity::action
如果無法導入Entity.py
,則可能需要將其包含的目錄添加到PYTHONPATH
環境變量中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.