我是 python 的初学者,对 C++ 有中级知识。我正在尝试在 c++ 中嵌入 python 代码。但是,我遇到了构建错误,以我目前的知识水平,我无法对其进行故障排除。请在这方面帮助我。以下是代码。
#include <iostream>
using namespace std;
#include <Python.h>
int main()
{
cout<<"Calling Python to find the sum of 2 and 2";
// Initialize the Python interpreter.
Py_Initialize();
// Create some Python objects that will later be assigned values.
PyObject *pName,*pModule, *pDict, *pFunc, *pArgs, *pValue;
// Convert the file name to a Python string.
pName = PyString_FromString("Sample.py"); // Import the file as a Python module.
pModule = PyImport_Import(pName);
// Create a dictionary for the contents of the module.
pDict = PyModule_GetDict(pModule);
// Get the add method from the dictionary.
pFunc = PyDict_GetItemString(pDict, "add");
// Create a Python tuple to hold the arguments to the method.
pArgs = PyTuple_New(2);
// Convert 2 to a Python integer.
pValue = PyInt_FromLong(2);
// Set the Python int as the first and second arguments to the method.
PyTuple_SetItem(pArgs, 0, pValue);
PyTuple_SetItem(pArgs, 1, pValue);
// Call the function with the arguments.
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
// Print a message if calling the method failed.
if(pResult == NULL)
cout<<"Calling the add method failed.\n";
// Convert the result to a long from a Python object.
long result = PyInt_AsLong(pResult);
// Destroy the Python interpreter.
Py_Finalize(); // Print the result.
cout<<"The result is"<<result;
cout<<"check";
return 0;
}
我收到以下错误:
pytest.exe 中 0x00000000 处的未处理异常:0xC0000005:访问冲突。
并且构建在pModule = PyImport_Import(pName);
文件 Sample.py 具有以下内容的行处中断:
# Returns the sum of two numbers.
def add(a, b):
return a+b
我正在使用 python 2.7 和 VS2010。我为此创建了一个 win32 控制台项目,并且正在发布模式下构建。我已将文件 Sample.py 复制到项目文件夹中。我无法弄清楚是什么导致构建崩溃。请帮助。