为什么Python / C API在PyRun_SimpleFile上崩溃? [英] Why does the Python/C API crash on PyRun_SimpleFile?

查看:676
本文介绍了为什么Python / C API在PyRun_SimpleFile上崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在C ++应用程序中嵌入不同的脚本语言,目前我在尝试Stackless Python 3.1。我尝试了几个教程和示例,我可以找到几个,尝试从应用程序运行一个简单的脚本。

I've been experimenting with embedding different scripting languages in a C++ application, currently I'm trying Stackless Python 3.1. I've tried several tutorials and examples, what few I can find, to try and run a simple script from an application.

Py_Initialize();

FILE* PythonScriptFile = fopen("Python Scripts/Test.py", "r");
if(PythonScriptFile)
{
    PyRun_SimpleFile(PythonScriptFile, "Python Scripts/Test.py");
    fclose(PythonScriptFile);
}

Py_Finalize();

由于某些奇怪的原因,运行此段代码会导致访问冲突:

For some odd reason, running this piece of code results in an access violation at:

    PyRun_SimpleFile(PythonScriptFile, "Python Scripts/Test.py");

我在网上搜索过类似问题的人,只找到一个。他们唯一的解决方案是一个解决方法,只是似乎可能在旧版本的Python:创建一个python文件对象,并返回 FILE * 从该python文件对象到 PyRun_SimpleFile 。这样的函数调用不可用,但是Python 3.1 API从文件描述符创建文件对象并返回文件描述符,但 PyRun_SimpleFile 函数仍然需要一个 FILE *

I've searched online for others with a similar problem and found only one. Their only solution was a workaround that only seems possible in an older version of Python: Creating a python file object and returning the FILE* from that python file object into PyRun_SimpleFile. Such function calls are not available however, the Python 3.1 API creates file objects from a file descriptor and returns file descriptors, but the PyRun_SimpleFile function still requires a FILE*.

我对于如何从文件中运行任何脚本感到失落,缺少将整个文件手动加载到内存并把它作为一个巨大的字符串运行,肯定不是一个实用的解决方案。

I'm at a loss as to how to run any scripts from file, short of loading the entire file into memory manually and running it as a giant string, certainly not a practical solution.

什么给了?如果API有内部错误,我该如何完成这个任务?

What gives? How can I accomplish this task if the API has an internal error?

更新:
我从源代码管理构建Stackless Python 3.1,崩溃保持完全不变,尽管使用相同的C运行时库。我的项目和Stackless Python 3.1源代码都是用Visual Studio 2010的C ++编译器和C运行库构建的。我不再有什么可以解决这个问题,没有修改Python使用文件名而不是FILE *。另一个可怕的解决方法。

Update: I've managed to build Stackless Python 3.1 from the source and yet the crash remains completely unchanged, despite using the same C runtime library. Both my project and the Stackless Python 3.1 source are built with Visual Studio 2010's C++ compiler and C runtime. I no longer have any inkling as to what might solve this problem, short of modifying Python to use a file name and not a FILE*. Another terrible workaround.

推荐答案

如下:

   PyObject* PyFileObject = PyFile_FromString("test.py", "r");
   PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "test.py", 1);

请注意,这是在 python 2.7 我不知道是否在3.x中的API已更改。

Note that this was in python 2.7 though. I don't know if the API has changed in 3.x.

这篇关于为什么Python / C API在PyRun_SimpleFile上崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆