title: From NSTextfield to (const unsigned char *) with Swift
body: <p>How can i properly received a (const unsigned char *) in a C program from a NSTextField in Swift ?</p>
  
  <p><strong>Case 1</strong> :  </p>
  
  <pre><code>let string1 = atextfield!.stringValue // -&gt; "Test"
  print(string1) // -&gt; "Test"
  </code></pre>
  
  <p>string1/_core/_baseAddress = nil // in debug</p>
  
  <pre><code>let string2 = string1.utf8CString.withUnsafeBytes
  {
      ptr -&gt; UnsafePointer&lt;UInt8&gt; in
      return ptr.load(as: UnsafePointer&lt;UInt8&gt;.self)
  }
  </code></pre>
  
  <p>fatal error: UnsafeRawBufferPointer.load out of bounds</p>
  
  <p><strong>Case 2</strong> : </p>
  
  <pre><code>let string1 = "Test"
  print(string1) // -&gt; "Test"
  </code></pre>
  
  <p>string1/_core/_baseAddress = (_rawValue = 0x... "Test") // in debug</p>
  
  <p>fatal error: UnsafeRawBufferPointer.load out of bounds</p>
  
  <p><strong>Case 3</strong> : </p>
  
  <pre><code>let string1 = atextfield!.stringValue // Value = "Test"
  print(string1) // -&gt; "Test"
  </code></pre>
  
  <p>string1/_core/_baseAddress = nil // in debug</p>
  
  <pre><code>let string2 :UnsafePointer&lt;UInt8&gt; = string1.utf8CString.withUnsafeBufferPointer {
  ($0.baseAddress!.withMemoryRebound(to: UnsafePointer&lt;UInt8&gt;.self, capacity: string1.lengthOfBytes(using: .utf8)) {$0})}.pointee
  
  testCPgm(string2)
  </code></pre>
  
  <p>testcfield = "" in testCPgm</p>
  
  <pre><code>void testCPgm(const unsigned char *testcfield)
  {
  
  }
  </code></pre>
  
  <p><strong>Case 4</strong> : </p>
  
  <pre><code>let string1 = "Test"
  print(string1) // -&gt; "Test"
  </code></pre>
  
  <p>string1/_core/_baseAddress = (_rawValue = 0x... "Test") // in debug</p>
  
  <p>testcfield = "" in testCPgm</p>
  
  <p><strong>Case 5</strong> --> <strong>It Works !</strong></p>
  
  <pre><code>let string1 = "Test"
  
  or
  
  let string1 = atextfield!.stringValue
  print(string1) // -&gt; "Test"
  
  testCPgm(string1) // Yes directly from String to (const unsigned char *)
  </code></pre>
  
  <p>testcfield = "Test" in testCPgm</p>
  
  <p>Thanks for answers</p>