我是一名Python初学者,拥有关于C++的中级知识。 我想在C++中嵌入python代码。但是,我得到一个构建错误,并且根据我目前的知识水平,我无法解决它。请在这方面给予我帮助。 以下是代码。在嵌入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;
}
我得到以下错误: 未处理的异常在00000000在pytest.exe:0000005:访问冲突。 并在行pModule = PyImport_Import(pName);
该文件的生成中断Sample.py具有内容:
# Returns the sum of two numbers.
def add(a, b):
return a+b
我使用python 2.7和VS2010.I已经创造了这个Win32控制台项目,我建设发布模式。我已将文件Sample.py复制到项目文件夹中。 我无法弄清楚是什么导致该构建崩溃。善良的帮助。
非常感谢您的回复。正如我所说,我是一名Python初学者。您可以提供任何资源,我可以从中了解错误处理。python/C api假设读者有很多知识。 – userXktape 2013-04-29 11:46:03
http://docs.python.org/2/c-api/intro.html#exceptions – 2013-04-29 22:00:39