c++ - 如何修复 C++ 中的 PyImport_Import(python35.dll 中的异常)

标签 c++ python-3.x python-embedding

我正在尝试一个非常基本的“hello world”程序,它应该在我的 C++ 控制台应用程序中嵌入一个 python 脚本,但它在 pModule = PyImport_Import(pName); 处失败并出现未指定的异常“访问违规阅读位置……”

我已经能够为没有定义和返回的 python 脚本运行 PyRun_SimpleFile(),但是对于我 future 的应用程序,我需要一个有返回值的 python 方法,所以 PyRun_SimpleFile() 不是一个选项。

我的代码,基于 this Introduction是:

主要.cpp

#include "stdafx.h"
#include <stdlib.h>
#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule;
    PyObject *pFunc, *pValue;

    pName = PyUnicode_FromString("HelloWorld");
    pModule = PyImport_Import(pName);
    Py_XDECREF(pName);

    if (pModule)
    {
        pFunc = PyObject_GetAttrString(pModule, "getInteger");
        if (pFunc && PyCallable_Check(pFunc))
        {
            pValue = PyObject_CallObject(pFunc, NULL);
            printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
            Py_XDECREF(pValue);
        }
        else
        {
            printf("ERROR: function getInteger()\n");
        }
        Py_XDECREF(pFunc);
    }
    else
    {
        printf_s("ERROR: Module not imported\n");
    }

    Py_XDECREF(pModule);

    Py_Finalize();
    return 0;
}

HelloWorld.py(在我的 VS2015 解决方案的调试位置):

def getInteger():
    print('Python function getInteger() called')
    c = 100*2
    return c

最佳答案

好吧,我相信您的代码中缺少一些指令,例如 Py_Initialize。我还会使用 PyImport_ImportModule 而不是 PyImport_Import。看看你可能会尝试的这个序列:

int main(int argc, char *argv[])
{
    Py_SetPythonHome(L"path/to/python/folder");
    Py_Initialize();
    //PySys_SetArgv(argc, argv); //optional, argv must be wchar_t
    PyObject *pFunc, *pValue;

    pModule = PyImport_ImportModule("HelloWorld");

    if (pModule)
    {
        pFunc = PyObject_GetAttrString(pModule, "getInteger");
        if (pFunc && PyCallable_Check(pFunc))
        {
            pValue = PyObject_CallObject(pFunc, NULL);
            printf_s("C: getInteger() = %ld\n", PyLong_AsLong(pValue));
            Py_XDECREF(pValue);
        }
        else
        {
            printf("ERROR: function getInteger()\n");
        }
        Py_XDECREF(pFunc);
    }
    else
    {
        printf_s("ERROR: Module not imported\n");
    }

    Py_XDECREF(pModule);

    Py_Finalize();
    return 0;
}

如果仍然无法正常工作,请尝试在 PyInitialize 之后添加:

PyRun_SimpleString(
    "import os, sys \n"
    "sys.path.append(os.getcwd()) \n"
);

同样在 PyInitialize 之后,您可以检查它是否使用 Py_IsInitialized 进行了初始化。

关于c++ - 如何修复 C++ 中的 PyImport_Import(python35.dll 中的异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56396346/

相关文章:

python - C++调用Python如何处理SystemExit异常

c++ - 为什么 (1/2)*x 不同于 0.5*x?

c++ - 在 rpi4 中使用 openCV 的 gstreamer

python - 通知用户运行unittest时是否引发特定异常

Python 引用调用问题

python - 如何将 PyFrameObject 转换为 PyObject

ubuntu - 无法从嵌入式 boost python 导入一些内置模块

c++ - 是否有对象的 `this` 的类似物,但用于函数?

c++ - 关于 OR ( || ) 运算符和 return 语句

python-3.x - numpy 矩阵中的绝对非对角差之和