从C++;具有名称空间 我试图从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); struct MyClass{ 无效日志(const std::string&s) { cout

从C++;具有名称空间 我试图从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); struct MyClass{ 无效日志(const std::string&s) { cout,python,c++,callback,boost-python,Python,C++,Callback,Boost Python,这是因为非局部作用域中的变量无法反弹。即使不调用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++,它也无法工作:

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()