2013-04-25 58 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