我在让基于 Python 2 的 C++ 引擎在 Python3 中工作时遇到了一些严重的问题。我知道整个 IO 堆栈已经改变,但我似乎尝试的一切都以失败告终。下面是前代码(Python2)和后代码(Python3)。我希望有人可以帮助我找出我做错了什么。我也boost::python
用来控制引用。
该程序应该通过映射将 Python 对象加载到内存中,然后在使用 run 函数时,它会找到加载到内存中的文件并运行它。我的代码基于来自 delta3d python 管理器的示例,它们加载到文件中并立即运行它。我在 Python3 中没有看到任何等效的东西。
Python2 代码从这里开始:
// what this does is first calls the Python C-API to load the file, then pass the returned
// PyObject* into handle, which takes reference and sets it as a boost::python::object.
// this takes care of all future referencing and dereferencing.
try{
bp::object file_object(bp::handle<>(PyFile_FromString(fullPath(filename), "r" )));
loaded_files_.insert(std::make_pair(std::string(fullPath(filename)), file_object));
}
catch(...)
{
getExceptionFromPy();
}
接下来我从 std::map 加载文件并尝试执行它:
bp::object loaded_file = getLoadedFile(filename);
try
{
PyRun_SimpleFile( PyFile_AsFile( loaded_file.ptr()), fullPath(filename) );
}
catch(...)
{
getExceptionFromPy();
}
Python3 代码从这里开始:这是我迄今为止基于这里的一些建议所得到的......所以问题 加载:
PyObject *ioMod, *opened_file, *fd_obj;
ioMod = PyImport_ImportModule("io");
opened_file = PyObject_CallMethod(ioMod, "open", "ss", fullPath(filename), "r");
bp::handle<> h_open(opened_file);
bp::object file_obj(h_open);
loaded_files_.insert(std::make_pair(std::string(fullPath(filename)), file_obj));
跑:
bp::object loaded_file = getLoadedFile(filename);
int fd = PyObject_AsFileDescriptor(loaded_file.ptr());
PyObject* fileObj = PyFile_FromFd(fd,fullPath(filename),"r",-1,"", "\n","", 0);
FILE* f_open = _fdopen(fd,"r");
PyRun_SimpleFile( f_open, fullPath(filename) );
最后,此时程序的一般状态是文件以 asTextIOWrapper
和 Run: 部分加载,返回的 fd 始终为 3 并且由于某种原因_fdopen
永远无法打开,FILE
这意味着我无法执行类似PyRun_SimpleFile
. 错误本身是ASSERTION
对_fdopen
. 有没有更好的方法来做这一切我真的很感激任何帮助。
如果您想查看 Python2 版本的完整程序,请访问Github