Záv*_*oix 5 c++ python boost boost-python
所以我正在开发一个小项目,我在其中使用Python作为嵌入式脚本引擎.到目前为止,我使用boost.python并没有遇到太多麻烦,但是如果可能的话,我还有一些事情要做.
基本上,Python可以通过向类添加函数甚至数据值来扩展我的C++类.我希望能够在C++方面保持这些,所以一个python函数可以将数据成员添加到类中,然后传递给另一个函数的同一个实例仍将拥有它们.这里的目标是用C++编写通用核心引擎,让用户以他们需要的任何方式在Python中扩展它,而不必触及C++.
所以我认为可行的是我将一个boost::python::objectC++类存储为一个值self,当从C++调用python时,我会发送该python对象boost::python::ptr(),以便python端的修改将持续回到C++类.不幸的是,当我尝试这个时,我收到以下错误:
TypeError: No to_python (by-value) converter found for C++ type: boost::python::api::object
有没有办法将一个对象直接传递给这样的python函数,或者我可以通过任何其他方式来实现我想要的结果?
在此先感谢您的帮助.:)
从c ++ sig邮件列表中获得了这个梦幻般的解决方案.
std::map<std::string, boost::python::object>在C++类中实现一个,然后重载__getattr__()并__setattr__()读取和写入该std :: map.然后boost::python::ptr()像往常一样将它发送到python ,不需要在C++端保留一个对象或者将一个对象发送到python.它完美地运作.
编辑:我还发现我必须以__setattr__()特殊方式覆盖该功能,因为它破坏了我添加的内容add_property().这些东西在获取它们时工作正常,因为python在调用之前会检查类的属性__getattr__(),但是没有这样的检查__setattr__().它只是直接调用它.所以我不得不做一些改变,把它变成一个完整的解决方案.以下是该解决方案的完整实现:
首先创建一个全局变量:
boost::python::object PyMyModule_global;
Run Code Online (Sandbox Code Playgroud)
按如下所示创建一个类(包含您要添加到其中的任何其他信息):
class MyClass
{
public:
//Python checks the class attributes before it calls __getattr__ so we don't have to do anything special here.
boost::python::object Py_GetAttr(std::string str)
{
if(dict.find(str) == dict.end())
{
PyErr_SetString(PyExc_AttributeError, JFormat::format("MyClass instance has no attribute '{0}'", str).c_str());
throw boost::python::error_already_set();
}
return dict[str];
}
//However, with __setattr__, python doesn't do anything with the class attributes first, it just calls __setattr__.
//Which means anything that's been defined as a class attribute won't be modified here - including things set with
//add_property(), def_readwrite(), etc.
void Py_SetAttr(std::string str, boost::python::object val)
{
try
{
//First we check to see if the class has an attribute by this name.
boost::python::object obj = PyMyModule_global["MyClass"].attr(str.c_str());
//If so, we call the old cached __setattr__ function.
PyMyModule_global["MyClass"].attr("__setattr_old__")(ptr(this), str, val);
}
catch(boost::python::error_already_set &e)
{
//If it threw an exception, that means that there is no such attribute.
//Put it on the persistent dict.
PyErr_Clear();
dict[str] = val;
}
}
private:
std::map<std::string, boost::python::object> dict;
};
Run Code Online (Sandbox Code Playgroud)
然后按如下所示定义python模块,添加您想要的任何其他defs和属性:
BOOST_PYTHON_MODULE(MyModule)
{
boost::python::class_<MyClass>("MyClass", boost::python::no_init)
.def("__getattr__", &MyClass::Py_GetAttr)
.def("__setattr_new__", &MyClass::Py_SetAttr);
}
Run Code Online (Sandbox Code Playgroud)
然后初始化python:
void PyInit()
{
//Initialize module
PyImport_AppendInittab( "MyModule", &initMyModule );
//Initialize Python
Py_Initialize();
//Grab __main__ and its globals
boost::python::object main = boost::python::import("__main__");
boost::python::object global = main.attr("__dict__");
//Import the module and grab its globals
boost::python::object PyMyModule = boost::python::import("MyModule");
global["MyModule"] = PyMyModule;
PyMyModule_global = PyMyModule.attr("__dict__");
//Overload MyClass's setattr, so that it will work with already defined attributes while persisting new ones
PyMyModule_global["MyClass"].attr("__setattr_old__") = PyMyModule_global["MyClass"].attr("__setattr__");
PyMyModule_global["MyClass"].attr("__setattr__") = PyMyModule_global["MyClass"].attr("__setattr_new__");
}
Run Code Online (Sandbox Code Playgroud)
完成所有这些后,您将能够将对python中的实例的更改持久保存到C++中.任何在C++中定义为属性的东西都将被正确处理,并且任何不会被附加到dict而不是类的东西__dict__.
| 归档时间: |
|
| 查看次数: |
2869 次 |
| 最近记录: |