KVISH
KVISH

Reputation: 13208

UnsafeMutablePointer calling function from Swift

I have a method defined as below in Objective-C:

- (BOOL)dataHandler:(void*)buffer length:(UInt32)length

In ObjC we call this method as so:

self [self dataHandler:(void*)[myNsString UTF8String] length:[myNsString length]];

When I see the prototype for this for Swift it comes out like this:

self.dataHandler(<#buffer: UnsafeMutablePointer<Void>#>, length: <#UInt32#>)

I'm trying it as per below and not able to make it work:

self.dataHandler(buffer: UnsafeMutablePointer(response!), length: count(response!))

I also tried:

 var valueToSend = UnsafeMutablePointer<Void>(Unmanaged<NSString>.passRetained(response!).toOpaque())
 self.dataHandler(buffer: valueToSend, length: count(response!))

Is there anything else I haven't tried? I read the below on this:

Get the length of a String

UnsafeMutablePointer<Int8> from String in Swift

Upvotes: 3

Views: 1293

Answers (1)

Martin R
Martin R

Reputation: 540065

Similar as in UnsafeMutablePointer<Int8> from String in Swift, you can send the response string as UTF-8 encoded bytes to the handler method with

response.withCString {
    self.dataHandler(UnsafeMutablePointer($0), length: UInt32(strlen($0)))
}

Inside the block, $0 is a pointer to a NUL-terminated array of char with the UTF-8 representation of the string.

Note also that your Objective-C code

[self dataHandler:(void*)[myNsString UTF8String] length:[myNsString length]]

has a potential problem: length returns the number of UTF-16 code points in the string, not the number of UTF-8 bytes. So this will not pass the correct number of bytes for strings with non-ASCII characters.

Upvotes: 3

Related Questions