2017-05-09 51 views
0

我有一個C++程序,裏面for循環,調用一個函數。 該函數做了一個繁重的過程,它嵌入了python,並執行圖像處理。C++ for循環是否需要運行時?

我的問題是,爲什麼它只能運行在變量的第一個實例。

主要功能//我只顯示的代碼的部分需要在這個標題

int main(){ 
for(int a = 0;a<5;a++){ 
    for(int b=0;b<5;b++){ 

// I want every increment it go to PyRead() function, doing image processing, and compare 
    if(PyRead()==1){ 
      // some application might be occur 
     } 
     else { 
     } 
    } 
} 

PyRead()函數,在C++函數進入蟒環境中執行的圖像處理

bool PyRead(){ 


string data2; 
Py_Initialize();  


     PyRun_SimpleString("print 'hahahahahawwwwwwwwwwwww' "); 
     char filename[] = "testcapture"; 


     PyRun_SimpleString("import sys"); 
     PyRun_SimpleString("sys.path.append(\".\")"); 

     PyObject * moduleObj = PyImport_ImportModule(filename); 
     if (moduleObj) 
     { 
      PyRun_SimpleString("print 'hahahahaha' "); 
      char functionName[] = "test"; 
      PyObject * functionObj = PyObject_GetAttrString(moduleObj, functionName); 
      if (functionObj) 
      { 
       if (PyCallable_Check(functionObj)) 
       { 
        PyObject * argsObject = PyTuple_New(0); 
        if (argsObject) 
        { 
        PyObject * resultObject = PyEval_CallObject(functionObj, argsObject); 
        if (resultObject) 
        { 
         if ((resultObject != Py_None)&&(PyString_Check(resultObject))) 
         { 
          data2 = PyString_AsString(resultObject); 
         } 
         Py_DECREF(resultObject); 
        } 
        else if (PyErr_Occurred()) PyErr_Print(); 

        Py_DECREF(argsObject); 
        } 
       } 
       Py_DECREF(functionObj); 
      } 
      else PyErr_Clear(); 

      Py_DECREF(moduleObj); 
     } 
Py_Finalize(); 


std::cout << "The Python test function returned: " << data2<< std::endl; 




cout << "Data2 \n" << data2; 

if(compareID(data2) == 1) 
    return true; 
else 
    return false; 
} 

這是我第二次在堆棧溢出問這個問題......我希望這個時候這個問題會更清楚〜!

我可以成功編譯沒有錯誤。 當我運行程序時,我意識到在a = 0,b = 0時它會去PyRead()函數並返回值,之後它會變爲a = 0,b = 1,那時整個程序將會最後,它想再次去PyRead()函數,但它並沒有做到這一點,直結束程序

我必須強烈地提到PyRead()函數需要一個很長的時間做(30秒)

我不知道發生什麼事,尋求somehelp ...請注重大膽部分明白我的問題

+0

換句話說,你的程序第二次崩潰,它調用PyRead? – immibis

+0

@immibis ya ...它崩潰了 – BeginProgramLife

+0

你的代碼在嘲笑你! –

回答

1

https://docs.python.org/2/c-api/init.html#c.Py_Finalize

理想的評論,這釋放由Python解釋器分配的所有內存。

由Python加載的動態加載擴展模塊不會被卸載。如果他們的初始化程序被調用不止一次

看來你的模塊

一些擴展可能無法正常工作,不使用此功能發揮好。

解決方法可以是 - 即時創建腳本並使用python子進程調用它。