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

我已经能够为没有定义和返回值的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

最佳答案

好吧,我相信您的代码中缺少一些说明,例如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初始化。

10-05 23:42
查看更多