[英]Pass a C++ object by reference/pointer to Python interpreter using Boost.Python
I have a C++ object and wish to pass it by reference/pointer to an embedded Python interpreter so that Python can make changes to it which are visible to both C++ and Python. 我有一个C ++对象,希望通过引用/指针将其传递给嵌入式Python解释器,以便Python可以对其进行更改,这对于C ++和Python都是可见的。 I am using Boost.Python for interop.
我正在使用Boost.Python进行互操作。
For sake of example, here is a class Foo
, its Boost.Python wrapper, and a Foo
object in C++: 举例来说,这是一个类
Foo
,其Boost.Python包装器和一个C ++中的Foo
对象:
mymodule.h : mymodule.h :
struct Foo
{
int bar;
Foo(int num): bar(num) {}
};
mymodule.cpp : mymodule.cpp :
#include "mymodule.h"
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(mymodule)
{
using namespace boost::python;
class_<Foo>("Foo", init<int>())
.def_readwrite("bar", &Foo::bar)
;
}
main.cpp : main.cpp :
#include <iostream>
#include <boost/python.hpp>
#include "mymodule.h"
using namespace boost::python;
int main()
{
Py_Initialize();
object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
import("mymodule");
Foo foo(42);
// ... somehow use Boost.Python to send reference to interpreter ...
object result = exec_file("myscript.py", main_namespace);
std::cout << foo.bar << std::endl;
}
So how do I send a reference of foo
to Python so both C++ and Python can see its contents? 那么,如何将
foo
的引用发送给Python,以便C ++和Python都能看到其内容?
In C++, prior to running the script, add: 在C ++中,在运行脚本之前,添加:
main_namespace["foo"] = ptr(&foo);
Now the Python environment will have a pointer to the C++ variable foo
and any changes made to it by a Python script will be performed on the C++ object rather than a copy. 现在,Python环境将具有指向C ++变量
foo
的指针,并且Python脚本对其所做的任何更改将在C ++对象而不是副本上执行。
If myscript.py
is: 如果
myscript.py
是:
foo.bar = 12
then the output of the cout
line at the end will be 12
, not 42
. 那么末尾的
cout
行的输出将是12
,而不是42
。
Note that you may want to place foo
inside the mymodule
namespace to self-document its origin, ie mymodule.foo.bar
. 请注意,您可能需要将
foo
放置在mymodule
命名空间中,以自我记录其来源,即mymodule.foo.bar
。
The Boost.Python documentation doesn't seem to describe this method of pass-by-pointer, but it works nonetheless. Boost.Python文档似乎没有描述这种通过指针的方法,但是仍然可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.