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

时间:2019-05-31 13:47:35

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

我正在尝试一个非常基本的“ hello world”程序,该程序应在我的C ++控制台应用程序中嵌入python脚本,但是它在pModule = PyImport_Import(pName);处失败,但未指定异常“访问冲突读取位置...” < / p>

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

基于this Introduction的我的代码是:

main.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

1 个答案:

答案 0 :(得分:2)

好吧,我相信您的代码中缺少一些说明,例如with open("foobar.properties", "rb") as f: p.load(f, "utf-8") 。我也将使用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初始化。