【发布时间】:2019-05-31 13:47:34
【问题描述】:
我正在尝试一个非常基本的“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
【问题讨论】:
标签: c++ python-3.x python-embedding