3

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

Community
  • 1
  • 1
KVISH
  • 12,923
  • 17
  • 86
  • 162

1 Answers1

3

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.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Can you explain to me what it does? And why does it have to be `response.withCString { }`, why can't it directly calling `dataHandler`? – KVISH Sep 16 '15 at 20:01
  • @KVISH: See update. You cannot call it directly because `String` is not a C string but a struct containing pointers to a representation of the string. – Martin R Sep 16 '15 at 20:06