2

I have a NSData in Objective-C, the NSData has value 0x10, code like bellows:

@implementation BufUtil
+ (NSData *_Nonnull) getOCBuf {
    std::vector<uint8_t> sendData = {0x10};
    NSData * reqBuf = [[NSData alloc] initWithBytesNoCopy:sendData.data() length:sendData.size() freeWhenDone:false];
    NSLog(@"getOCBuf, oc NSData reqBuf:%@", reqBuf);
    return reqBuf;
}
@end

Then I use the data in Swift, Swift auto convert Objective-C NSData to Swift Data, but strange things happen, the value in Swift Data is 0x60, code like belows:

public func getOCBuf() -> Data {
    let data = BufUtil.getOCBuf();
    print("getOCBuf: swift data: \(data.hexEncodedString())")
    return data
}

the log is like:

getOCBuf, oc NSData reqBuf:{length = 1, bytes = 0x10}
getOCBuf: swift data: 60

Now I am confused with what happened. Why 0x10 turn into 0x60, the two number not Binary complement.

Can anybody help me, thanks.

the code:
https://github.com/oncealong/SwiftOcDataConvert

bluesky
  • 145
  • 7
  • std::vector seems more c++ than Objective-C. That may be the problem. You may find useful information in this [post](https://stackoverflow.com/questions/8713514/stdvector-in-objective-c-method) – Ptit Xav Dec 04 '21 at 13:35

1 Answers1

0

It's my falut.

I copy code "how to convert from std::vector to NSData" from stackoverflow, but the code use [NSData alloc] initWithBytesNoCopy, which lead to all this.

the momory associate with the std::vector has freed after the getOCBuf func return. but the oc NSData and swift Data don't know. it use the origin address and found different value.

To be honest, the app should be crashed, and give a reason.

bluesky
  • 145
  • 7