0

How can i properly received a (const unsigned char *) in a C program from a NSTextField in Swift ?

Case 1 :

let string1 = atextfield!.stringValue // -> "Test"
print(string1) // -> "Test"

string1/_core/_baseAddress = nil // in debug

let string2 = string1.utf8CString.withUnsafeBytes
{
    ptr -> UnsafePointer<UInt8> in
    return ptr.load(as: UnsafePointer<UInt8>.self)
}

fatal error: UnsafeRawBufferPointer.load out of bounds

Case 2 :

let string1 = "Test"
print(string1) // -> "Test"

string1/_core/_baseAddress = (_rawValue = 0x... "Test") // in debug

fatal error: UnsafeRawBufferPointer.load out of bounds

Case 3 :

let string1 = atextfield!.stringValue // Value = "Test"
print(string1) // -> "Test"

string1/_core/_baseAddress = nil // in debug

let string2 :UnsafePointer<UInt8> = string1.utf8CString.withUnsafeBufferPointer {
($0.baseAddress!.withMemoryRebound(to: UnsafePointer<UInt8>.self, capacity: string1.lengthOfBytes(using: .utf8)) {$0})}.pointee

testCPgm(string2)

testcfield = "" in testCPgm

void testCPgm(const unsigned char *testcfield)
{

}

Case 4 :

let string1 = "Test"
print(string1) // -> "Test"

string1/_core/_baseAddress = (_rawValue = 0x... "Test") // in debug

testcfield = "" in testCPgm

Case 5 --> It Works !

let string1 = "Test"

or

let string1 = atextfield!.stringValue
print(string1) // -> "Test"

testCPgm(string1) // Yes directly from String to (const unsigned char *)

testcfield = "Test" in testCPgm

Thanks for answers

Stephane
  • 391
  • 1
  • 2
  • 13

1 Answers1

0

This is what i found without closure.

From String (string1) to (const unsigned char *) (string2)

let string2 = UnsafeRawPointer(string1.cString(using: .utf8)).bindMemory(to: CUnsignedChar.self, capacity: string1.lengthOfBytes(using: .utf8))

I don't know if there is a more elegant way to do it.

i don't found the equivalent for Data (without closure) (not NSData ( use .bytes))

Stephane
  • 391
  • 1
  • 2
  • 13