将Python嵌入到C++中

4
我使用Borland C++创建了一个VCL应用程序。在我的项目中,有一个文件,在其中我已经实现了嵌入式Python在同一文件中定义的方法中(我的应用程序包含一个按钮,调用其中嵌入了Python的方法)。当我编译时,构建成功。但是当我运行应用程序并单击按钮时,它显示运行时错误:“模块“PYTHON25.DLL”中地址1E091375处的访问冲突。读取地址00000004”。请帮忙解决。 我以前从未使用过Python。 我的程序:
#pragma hdrstop

#include <fstream>
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>


#include "Python.h"

#include "Unit1.h"
#include "Unit2.h"
#pragma link "python25_bcpp.lib"

//---------------------------------------------------------------------------

#pragma package(smart_init)

bool callHelloWorld(int intVal)
{
    char fName[] = "Hello"; //file name
    char cFunc[] = "hello"; //method name

    char *pfName, *pcFunc;

    PyObject *pName, *pModule, *pDict, *pFunc ;

    pfName = fName;
    pcFunc = cFunc;

    Py_Initialize();

    pName = PyString_FromString(pfName);

    pModule = PyImport_Import(pName);

    pDict = PyModule_GetDict(pModule);

    pFunc = PyDict_GetItemString(pDict, pcFunc);

    if (PyCallable_Check(pFunc))
    {
        PyObject_CallObject(pFunc, NULL);
    } else
    {
        PyErr_Print();
    }


    // Py_DECREF(pModule);
    // Py_DECREF(pName);

    Py_Finalize();

    return 0;
}

3
我好像记得 Borland C++ 使用了不同的调用约定(fastcall?)。你的 python.dll 是使用相同的编译器编译的吗? - cdarke
python25.dll在C:\Windows\SysWOW64中。我没有编译它。 - Amit Mandal
我已经将所有的文件,如.h、lib和.dll文件都放在源文件夹中。我认为问题出在加载Hello.py模块上。您能否建议我如何成功地加载该模块? - Amit Mandal
1
这不会是调用约定,因为 python.h 将指定 cdecl。为了帮助我们,您能告诉我们哪一行失败了吗? - David Heffernan

[BCC32错误] python25.dll(1):E2141声明语法错误 完整的解析器上下文 Unit2.cpp(19):#include python25.dll

[BCC32错误] python25.dll(3):E2206非法字符'$'(0x24) 完整的解析器上下文 Unit2.cpp(19):#include python25.dll

[BCC32错误] python25.dll(4):E2206非法字符'?'(0xe) 完整的解析器上下文 Unit2.cpp(19):#include python25.dll [BCC32错误] python25.dll(1):E2206非法字符''(0x0)
- Amit Mandal
显示剩余3条评论
2个回答

1

检查PyImport_Import的返回值(模块是否在搜索路径中?)和PyDict_GetItemString

如果这些都没有帮助,请在您的应用程序中放置一些跟踪消息,以查看它崩溃的位置。


1
这对我有用:
只需删除 Py_Finalize() 我在另一个网站上读到,Py_Finalize 在特定情况下(如线程)存在一些问题。

多年过去了,问题依旧,解决方案也依然不变。对于Python 3,可以使用Py_FinalizeEx函数。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接