title: How can I pass a swift Data struct to C code and vice versa?
body: <p>I am trying to pass a byte array+length to C and since swift is using the existing Data struct to store byte array with the length built into it, I would like to know how to pass a swift Data struct to C complete with a replica Data struct in C</p>
  
  <p>A corollary is how can I also return a Data struct from C to swift?</p>
  
  <p>I have tried to create a corresponding Data struct in the C header file:</p>
  
  <pre><code>typedef struct {
      const char *data;
      unsigned int count;
  } CData;
  </code></pre>
  
  <p>In my swift code I tried to marshal the the byte content from the swift Data struct to the CData struct:</p>
  
  <pre><code>let swiftString = "Swift String"
  let testString: [CChar]? = swiftString.cString(using: .utf8)
  var data = Data()
  data.append(contentsOf: Array(swiftString.utf8))
  
  var cData = UnsafeMutablePointer&lt;CData&gt;.allocate(capacity: 1)
  defer {
      cData.deallocate()
  }
  cData.pointee.count = UInt32(data.count)
  cData.pointee.data = UnsafePointer(UnsafeMutablePointer&lt;Int8&gt;.allocate(capacity: data.count))
  defer {
      cData.pointee.data.deallocate()
  }
  data.copyBytes(to: cData.pointee.data, count: data.count) // Cannot convert value of type 'UnsafePointer&lt;Int8&gt;?' to expected argument type 'UnsafeMutablePointer&lt;UInt8&gt;'
  
  }
  </code></pre>
  
  <p>However, I get the error 
  Cannot convert value of type 'UnsafePointer?' to expected argument type 'UnsafeMutablePointer'
  when I try to copy the byte content from Data to CData</p>