2013-03-08 388 views
1

我在創建一個應用程序,其中OpenCV中的Mat圖像使用cv::imencode編碼爲base64字符串。爲此,我必須將vector<unsigned char>轉換爲const unsigned char*將vector <unsigned char>轉換爲const unsigned char *

我該怎麼做?

vector<unsigned char> buffer; 

vector<int> compression_params; 
compression_params.push_back(CV_IMWRITE_PXM_BINARY); 
compression_params.push_back(0); 

if(!cv::imencode(".ppm", desc, buffer, compression_params)){ 
    printf("Image encoding failed"); 
} 

// This generates a error 
string output = base64_encode(buffer.data(), buffer.size()); 
printf("Output: %s", output.c_str()); 

這是我的錯誤:EXC_BAD_ACCESS (code=1, address=0x2ffd7000)

更新


現在,它不會產生任何錯誤的了,但在轉換的地方出了差錯;輸出與解碼後的輸入不同,它主要由A字符組成。這是當前的腳本:

vector<unsigned char> buffer; 

vector<int> compression_params; 
compression_params.push_back(CV_IMWRITE_PXM_BINARY); 
compression_params.push_back(1); 

if(!cv::imencode(".pgm", desc, buffer, compression_params)){ 
    printf("Image encoding failed"); 
} 

string output = base64_encode(buffer.data(), buffer.size()); 
printf("Output: %s", output.c_str()); 

我不認爲這應該是另外一個問題,因爲我的猜測是,向量之間的轉換爲const無符號字符食堂的結果了; base64_encode曾經工作過。

+1

'buffer.data()已經'是一個'const的無符號字符*',所以沒有必要'reinterpret_cast'(如果你不使用C++ 11編譯器,你可以執行'&buffer [0]')。另外,發佈你的實際錯誤信息將會非常有用......否則,人們會猜測問題是什麼。 – Cornstalks 2013-03-08 14:16:14

+0

我得到這個錯誤,當我刪除它:'對象0x41444967 malloc:***錯誤:被釋放的指針沒有被分配',當我使用'&buffer [0]'我得到'EXC_BAD_ACCESS(code = 1,address = 0x2ffd7000)' – tversteeg 2013-03-08 14:17:29

+1

此外,我不會''c_str()'...只是將'string'分配給'string'。如果'base64_encode'返回的'string'內存在你嘗試執行任務時被釋放(因爲它是一個臨時的),我不會感到驚訝(我可能是錯誤的,但我仍然不會調用'.c_str()',因爲它阻止了正確的移動語義)。 – Cornstalks 2013-03-08 14:19:59

回答

3

一個主要問題是:

const char* s = base64_encode(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size()).c_str(); 

這裏,base64_encode功能可按返回一個std::string。然後您調用c_str()方法,該方法返回指向底層緩衝區的指針。然而,std::string然後立即超出範圍,給你一個懸掛指針。

此外,根本不需要reinterpret_cast。由於懸掛指針,您會遇到未定義行爲,這與演員陣容無關。

您應將其更改爲

std::string s = base64_encode(buffer.data(), buffer.size()); 
+0

我刪除'reinterpret_cast'並創建一個新的'字符串'變量,但都沒有工作;我仍然得到同樣的錯誤。之後,我將壓縮參數更改爲寫入二進制文件;現在我不會再有任何錯誤,但生成的字符串不正確。 – tversteeg 2013-03-08 14:53:22

+0

@ThomasVersteeg:好的,什麼是'cv :: imencode(「。pgm」,desc,buffer,compression_params)',你能向我們展示文檔,特別是它如何填充緩衝區。另外,你可以在調用之前插入一個buffer.size()的cout,以確保它是你想要的。 – 2013-03-08 15:20:53

+0

這裏是關於cv :: imencode的文檔:http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html和我應該在哪裏緩衝buffer.size()? – tversteeg 2013-03-08 15:23:23

相關問題