I am trying a really basic "hello world" program, which should embedd a python script in my C++ console application, but it fails at pModule = PyImport_Import(pName);
with an unspecified exception "Access violation reading location ..."
I was already able to run PyRun_SimpleFile()
for a python script without definitions and returns, but for my future application I need a python method with returns, so PyRun_SimpleFile()
is not an option.
My code, based on this Introduction is:
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 (in Debug Location of my VS2015 Solution):
def getInteger():
print('Python function getInteger() called')
c = 100*2
return c