简体   繁体   English

在C ++中嵌入Python的错误:无法读取内存

[英]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. 我正在尝试将Python嵌入VS C ++,但遇到了此错误:无法读取内存。 The C++ code is C ++代码是

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. pName包含对于注释行都“无法读取内存”的属性。 So, the PyImport_Import doesn't work as a result, pModule is NULL. 因此,PyImport_Import无效,pModule为NULL。 I've set PYTHONPATH in the environment variable and set argv[1] to Test001. 我已经在环境变量中设置了PYTHONPATH,并将argv [1]设置为Test001。 The file Test001.py is in the same folder as the .exe. 文件Test001.py与.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. 我已经使用Visual Studio 2013和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 : 我唯一的问题是调试链接需要python27_d.lib,我不得不使用以下方法解决该问题:

#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. 您还应该检查要链接的python版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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