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

2
  • What type has response? Commented Sep 16, 2015 at 19:10
  • It was a String in Swift Commented Sep 16, 2015 at 19:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.