【发布时间】:2021-01-30 17:49:56
【问题描述】:
我在 C++ 代码中定义了类,并像这样添加到 python 字典中:
try
{
Py_Initialize();
}
catch (bp::error_already_set &)
{
parse_python_exception();
}
main_module = bp::import("__main__");
main_namespace = main_module.attr("__dict__");
bp::class_<Gamefunctions> gamefunctions_binding = bp::class_<Gamefunctions>("Gamefunctions");
m_localDictionary["Gamefunctions"] = gamefunctions_binding;
m_localDictionary["gamefunctions"] = bp::ptr(&gamefunctions);
void (Gamefunctions::*addlog_comp)(string, string, string, bool) = &Gamefunctions::addlog;
void (Gamefunctions::*addlog_simp)(string, bool) = &Gamefunctions::addlog;
gamefunctions_binding.def("addlog", addlog_comp);
gamefunctions_binding.def("addlog", addlog_simp);
Py_Initialize();
bp::object execute;
string testcode = "def calllog():\n";
testcode += " gamefunctions.addlog(\"logmessage\", True)\n";
testcode += "gamefunctions.addlog(\"logmessage\", True)\n";
testcode += "calllog()";
try
{
execute = exec((testcode).c_str(), main_namespace, m_localDictionary);
}
catch (bp::error_already_set &)
{
parse_python_exception();
}
我尝试从 python 文件中的函数调用它,如下所示:
def calllog():
gamefunctions.addlog("logmessage",True)//not found
gamefunctions.addlog("logmessage",True)//works fine
calllog()
来自“def”外部的调用完美运行,但是当我从“def”调用它时,它给了我这个错误消息:
全局名称 'gamefunctions' 不是 定义
如何在'calllog()' 函数中“定义”'gamefunction' 类?
抱歉我的英语不好,感谢您提供的任何建议。
【问题讨论】:
-
如果您提供minimal reproducible example 会有所帮助。也许,您甚至会自己从代码中提取错误。
-
真的只是这里缺少的定义和调用,但如果这样更容易理解,我不会偷懒。