简体   繁体   中英

Error of embedding Python in C++ : unable to read memory

I'm trying to embed Python in VS C++ but I've encountered this error : unable to read memory. The C++ code is

Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
pName = PyBytes_FromString("Test001");
//pName = PyBytes_FromString(argv[1]);
pModule = PyImport_Import(pName);

The pName contains attributes which are "unable to read memory", both for the line commented. So, the PyImport_Import doesn't work as a result, pModule is NULL. I've set PYTHONPATH in the environment variable and set argv[1] to Test001. The file Test001.py is in the same folder as the .exe. I could not see the problem, I think there are some problems of configuration.

Thanks for help in advance!

I have tried your code with success using Visual Studio 2013 and Python 2.7. The only issue I had was with the link in debug which required a python27_d.lib and i had to solve the issue using :

#ifdef _DEBUG
#undef _DEBUG
#include <python.h>
#define _DEBUG
#else
#include <python.h>
#endif

You should also check which version of python you are linking against.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM