Search code examples
iosobjective-cxcodensdatastdvector

How to convert std::vector<uchar> to NSData when using C++ file iOS project


When using C++ file for algorithm execution in iOS Project,I came across a problem where a function returns std::vector data of jpeg image.

I have been searching for this particular question of how to convert from std::vector< uchar > to NSData and convert it to UIImage.

But unfortunately found none with lot of trial and error I came across a solution which I am posting along with this question.


Solution

  • To understand std::vector< uchar > is a byte array.

    To convert it to NSData we need to use the following approach

    1. Here getFrontFaceJPEG() is a C++ function which returns Jpeg data in the form of std::vector< uchar > std::vector<uchar> vectorImg = img.getFrontFaceJPEG();

    2. Once it returns std::vector< uchar > we need to convert it to NSData using below method: NSData * imgData = [[NSData alloc] initWithBytesNoCopy:vectorImg.data() length:vectorImg.size() freeWhenDone:false];

    3. Finally you can convert to UIImage UIImage *resultimage = [UIImage imageWithData:imgData];