使用命名空间从 C++ 调用 Python 函数
Calling Python functions from C++ with namespace
我正在尝试从 c++ 执行 Python 代码,该代码将定义 Python 函数并将其传回 c++,以便可以从那里回调。这工作正常,但问题是我无法为 Python 函数提供它最初定义时的名称空间。
struct MyClass {
void log(const std::string & s)
{
cout << s << endl;
}
void callFnct(PyObject * fnct)
{
bp::call<void>(fnct);
bp::call<void>(fnct);
}
};
bp::class_<MyClass, boost::noncopyable> plugin("Plugin", bp::no_init);
plugin.def("callFnct", &MyClass::callFnct);
std::unique_ptr<MyClass> cls(new MyClass());
bp::object main_module = bp::import("__main__");
bp::object main_namespace = main_module.attr("__dict__");
bp::dict locals;
locals["plugin"] = bp::object(bp::ptr(cls.get()));
std::string scriptSource =
"a=5\n"
"def my_func():\n"
" a+=1\n"
" plugin.log('won't work %d' % a)\n"
"plugin.log('this works')\n"
"plugin.callFnct(my_func)";
bp::object obj = bp::exec(bp::str(scriptSource), main_namespace, locals);
对 plugin.log()
的初始调用有效,但是一旦我们在 callFnct()
中调用 python 函数,命名空间就消失了,所以它看不到变量 a
或 plugin
模块。
有谁知道如何通过保留名称空间和将变量 a
保留在范围内来实现 bp::call<void>(fnct)
?
那是因为非本地范围内的变量不能被反弹。即使不调用 C++,它也不会工作:
a = 5
def my_func():
a += 5
print(a)
my_func()
UnboundLocalError: local variable 'a' referenced before assignment
您需要先导入它:
a = 5
def my_func():
global a
a += 5
print(a)
my_func()
我正在尝试从 c++ 执行 Python 代码,该代码将定义 Python 函数并将其传回 c++,以便可以从那里回调。这工作正常,但问题是我无法为 Python 函数提供它最初定义时的名称空间。
struct MyClass {
void log(const std::string & s)
{
cout << s << endl;
}
void callFnct(PyObject * fnct)
{
bp::call<void>(fnct);
bp::call<void>(fnct);
}
};
bp::class_<MyClass, boost::noncopyable> plugin("Plugin", bp::no_init);
plugin.def("callFnct", &MyClass::callFnct);
std::unique_ptr<MyClass> cls(new MyClass());
bp::object main_module = bp::import("__main__");
bp::object main_namespace = main_module.attr("__dict__");
bp::dict locals;
locals["plugin"] = bp::object(bp::ptr(cls.get()));
std::string scriptSource =
"a=5\n"
"def my_func():\n"
" a+=1\n"
" plugin.log('won't work %d' % a)\n"
"plugin.log('this works')\n"
"plugin.callFnct(my_func)";
bp::object obj = bp::exec(bp::str(scriptSource), main_namespace, locals);
对 plugin.log()
的初始调用有效,但是一旦我们在 callFnct()
中调用 python 函数,命名空间就消失了,所以它看不到变量 a
或 plugin
模块。
有谁知道如何通过保留名称空间和将变量 a
保留在范围内来实现 bp::call<void>(fnct)
?
那是因为非本地范围内的变量不能被反弹。即使不调用 C++,它也不会工作:
a = 5
def my_func():
a += 5
print(a)
my_func()
UnboundLocalError: local variable 'a' referenced before assignment
您需要先导入它:
a = 5
def my_func():
global a
a += 5
print(a)
my_func()