【发布时间】:2013-09-21 08:59:43
【问题描述】:
我在使用 Boost-Python 为 Python 封装枚举时遇到问题。
最初我打算在 try-catch (我在下面插入我的整个代码)语句中执行以下操作:
main_namespace["Motion"] = enum_<TestClass::Motion>("Motion")
.value("walk", TestClass::walk)
.value("bike", TestClass::bike)
;
一切正常,编译完成。在运行时我收到了这个错误(这对我来说毫无意义):
AttributeError: 'NoneType' object has no attribute 'Motion'
之后我决定在我的代码中使用 BOOST_PYTHON_MODULE 编写一个 Python 模块。 初始化 Python 解释器后,我想立即使用这个模块,但不知道如何(?)。以下是我的全部代码:
#include <boost/python.hpp>
#include <iostream>
using namespace std;
using namespace boost::python;
BOOST_PYTHON_MODULE(test)
{
enum_<TestClass::Motion>("Motion")
.value("walk", TestClass::walk)
.value("bike", TestClass::bike)
;
}
int main()
{
Py_Initialize();
try
{
object pyMainModule = import("__main__");
object main_namespace = pyMainModule.attr("__dict__");
//What previously I intended to do
//main_namespace["Motion"] = enum_<TestClass::Motion>("Motion")
// .value("walk", TestClass::walk)
// .value("bike", TestClass::bike)
//;
//I want to use my enum here
//I need something like line below which makes me able to use the enum!
exec("print 'hello world'", main_namespace, main_namespace);
}
catch(error_already_set const&)
{
PyErr_Print();
}
Py_Finalize();
return 0;
}
任何关于在 Python 中封装和使用枚举的有用信息都将不胜感激! 提前致谢
【问题讨论】:
标签: python boost boost-python