2013-04-25 52 views
0

我是一名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复制到项目文件夹中。 我无法弄清楚是什么导致该构建崩溃。善良的帮助。

回答

0

首先,缩进你的代码,MSVC甚至有一个选项可以自动完成它!毕竟,你希望人们在这里阅读它,所以去清理它。然后,不要在C++中初始化它们而不声明变量。这表明您可以从哪里使用它们。最后,无论何时调用函数,都要检查其结果是否有错误。默认情况下,只有throw std::runtime_error("foo() failed");出现错误。更详细地说,你可以尝试从Python中检索和添加错误信息。

现在,您的直接错误是使用空指针,如果您检查了返回值,您将避免使用该指针。在编写代码以正确检测错误之后,接下来我要看的是Python解释器的缺失初始化。你已经有一个评论,但评论不计算在内。我猜如果你已经实现了适当的错误处理,Python也会告诉你有关缺少的初始化。

+0

非常感谢您的回复。正如我所说,我是一名Python初学者。您可以提供任何资源,我可以从中了解错误处理。python/C api假设读者有很多知识。 – userXktape 2013-04-29 11:46:03

+0

http://docs.python.org/2/c-api/intro.html#exceptions – 2013-04-29 22:00:39