簡體   English   中英

嵌入python-(在我導入文件的地方)時發生構建錯誤

[英]Build error in embedding python-(where I import the file)

我是python的初學者,並且具有有關C ++的中級知識。 我正在嘗試將python代碼嵌入c ++中。 但是,我遇到了一個構建錯誤,以我目前的知識水平,我無法對其進行故障排除。在這方面請幫我。 以下是代碼。

    #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);處中斷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文件復制到了項目文件夾中。 我無法弄清楚是什么導致構建崩潰。請幫忙。

首先,縮進您的代碼,MSVC甚至可以選擇自動執行! 畢竟,您想讓這里的人閱​​讀它,所以去整理一下。 然后,不要在不使用C ++對其進行初始化的情況下聲明變量。 這使您可以從何處清楚地使用它們。 最后,無論何時調用函數,都要檢查其結果是否有錯誤。 默認情況下,只throw std::runtime_error("foo() failed"); 錯誤。 更詳細地說,您可以嘗試從Python檢索並添加錯誤信息。

現在,您的直接錯誤是使用了空指針,如果您檢查了返回值,則可以避免。 編寫代碼以正確檢測到該錯誤之后,我接下來要看的是缺少Python解釋器的初始化。 您已經有評論,但評論不算在內。 我想如果您實施了正確的錯誤處理,Python也會告訴您缺少的初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM