|
|
|
|
| 请教一个用boost.python在应用程序中嵌入python问题? |
|
|
|
[Original]
[Print]
[Top]
|
我想在自己的C++(Linux下开发)程序里嵌入Python,让它可以使用Python程序作为脚本。 Python脚本可以读/写C++程序里面的变量、使用C++里面的类和函数.
现在遇到一个问题:
如何把C++的一个自定义的类对象实例传递给python, 并在脚本中访问(简单对象的传递已基本搞定)。
代码:
#include <boost/python.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/python/class.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <iostream>
#include <string>
#include <list>
#include <map>
using namespace std;
namespace python = boost::python;
class Base
{
public:
Base(int x)
{
i = x;
}
virtual ~Base() {};
virtual void hello()
{
};
private:
int i;
};
BOOST_PYTHON_MODULE(embedded_hello)
{
using namespace boost::python;
class_<Base>("Base", init<int>())
// Add a regular member function.
.def("hello", &Base::hello)
;
}
int main()
{
// Register the module with the interpreter
if (PyImport_AppendInittab("embedded_hello", initembedded_hello) == -1)
throw std::runtime_error("Failed to add embedded_hello to the interpreter's "
"builtin modules");
// Initialize the interpreter
Py_Initialize();
// Retrieve the main module
python::object main_module((
python::handle<>(python::borrowed(PyImport_AddModule("__main__")))));
// Retrieve the main module's namespace
python::object main_namespace((main_module.attr("__dict__")));
Base * pBase = new Base(2000);
main_namespace["retValue"] = 5; // it is ok here
PyObject *arglist = Py_BuildValue( "(o)", pBase );;
main_namespace["AppBase"] = arglist; //here abort
python::handle<> result(
PyRun_String(
"from embedded_hello import *
"
"print retValue
"
"print AppBase.i
"
"hi = Base(500)
"
"hi2 = Base(1000)
",
Py_file_input, main_namespace.ptr(), main_namespace.ptr())
);
// Result is not needed
result.reset();
Py_Finalize();
}
请教一下该怎么显式传递对象? 多谢 !
|
|
|
[Original]
[Print]
[Top]
|
|
|