NSData * to std :: vector <unsigned char> No copy
If I have NSData * from one API and need to turn it into std :: vector for another API, is there a way to do this safely without copying bytes to NSData (suppose very large NSData *)?
There is no quick fix that comes to mind, no.
If you create an NSData object (rather than returning it to another API), you might consider subclassing NSData and / or NSMutableData when you really need to avoid copying - then you can access the repository (for example, std :: vector).
In some cases, you can also sneak around it by creating data using "your" selection:
NSData * data([[NSData alloc] initWithBytesNoCopy:vector.data() length:vector.size() freeWhenDone:false]); Of course, you need to make sure that the vector is not changed (or its backup storage is redistributed) before the NSData object is freed.
Sometimes you also need to consider changing the type of the parameter so that it is not std::vector . A small container that has an NSData element and a vector interface, an iterator, or a start + end can be adequate when placing other types of collections.
I don't know enough about stl or cpp, but if you can build a vector from the void * buffer, you should be able to:
void * buffer = [data bytes]; size_t len = [data length]; Keep in mind that data owns a buffer, so you cannot free it.