Search code examples
objective-carraysswiftbytensdata

BytesArray. ObjC to Swift


I am trying to write Swift implementation of the following ObjC(header file) code.

#include <stddef.h>
#ifndef VO_CERTIFICATE_TYPE
#define VO_CERTIFICATE_TYPE
typedef struct _voCertificate
{
  const char* bytes;
  size_t length;
}
voCertificate;

#endif 

static const char myCertificate_BYTES[] =
{
  103,  92,   -99,  33,   72,   48,   119,  -72,  
  -77,  75,   -88,  81,   113,  -46,  -119, -119, 
  5,    42,   -33,  94,   23,   3,    -112, 34,   
  -63,  75,   -77,  26,   -41,  -69,  50,   71,   
  19,   121,  109,  -60,  40,   18,   46,   -86, 
   .......... 
};
voCertificate const myCertificate =
{
  myCertificate_BYTES,
  sizeof(myCertificate_BYTES)
};
//////////////////////////////////////
NSData *certificate = [NSData dataWithBytes:myCertificate.bytes length:myCertificate.length];

My best assumption was:

 let myCertificate = [
          103,  92,   -99,  33,   72,   48,   119,  -72,  
          -77,  75,   -88,  81,   113,  -46,  -119, -119, 
          5,    42,   -33,  94,   23,   3,    -112, 34,   
          -63,  75,   -77,  26,   -41,  -69,  50,   71,   
          19,   121,  109,  -60,  40,   18,   46,   -86,
    ........................]

     var certificate = NSData(bytes: myCertificate as [Byte], length: myCertificate.count)

I tried to reach ObjC variable through Bridging-Header too, but there was "Undefined symbols for architecture armv7" error. I would really appreciate any help.


Solution

  • Your biggest problem is that the type of your myCertificate array is Int not Int8. Here is something that is working for me. Note I reconstructed the array from the NSData object to see if everything came out ok.

    let myCertificate = Array<Int8>(arrayLiteral:
        103,   92,  -99,   33,   72,   48,   119,   -72,
        -77,   75,  -88,   81,  113,  -46,  -119,  -119,
          5,   42,  -33,   94,   23,    3,  -112,    34,
         -63,  75,  -77,   26,  -41,  -69,    50,    71,
        19,   121,  109,  -60,   40,   18,    46,   -86)
    
    var certificate = NSData(bytes: myCertificate, length: myCertificate.count)
    
    var buffer = [Int8](count: certificate.length, repeatedValue: 0)
    certificate.getBytes(&buffer, length: certificate.length)
    

    enter image description here