简体   繁体   中英

Converting vector<unsigned char> to const unsigned char*

I'm trying to create an application where a Mat image in OpenCV is encoded using cv::imencode to a base64 string. For this I must convert a vector<unsigned char> to a const unsigned char* .

How can I do this?

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());

This is the error I get: EXC_BAD_ACCESS (code=1, address=0x2ffd7000)

Update


Now it doesn't generate any error's anymore, but somewhere in the conversion something goes wrong; the output isn't what the same as the input after I decoded it, it mostly consists of A character. This is the current script:

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());

I don't think this should be another question because my guess is that the conversion between vector to const unsigned char messes the result up; the base64_encode worked the previous time.

One major problem is:

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

Here, the base64_encode funciton is returning a std::string . You are then calling the c_str() method, which returns a pointer to the underlying buffer. HOWEVER, the std::string then immediately goes out of scope, leaving you with a dangling pointer.

Furthermore, the reinterpret_cast should not be needed at all. You're running into Undefined Behavior due to the dangling pointer, which has nothing to do with the cast.

You should change it to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM