3

I have a library which has a function like this:

int get_user_name(const char **buffer);

in swift, should call like this:

var name:CMutablePointer<CString> = nil
get_user_name(name)

I want make use this function more comfortable so I wrapped this up:

func get_username() -> String {
    var name:CMutablePointer<CString> = nil
    get_user_name(name)

    // how to convert name to String
}

I question is how to convert name to String

galilio
  • 307
  • 1
  • 3
  • 13

2 Answers2

5

It goes something like:

 var stringValue :CString = ""

 name.withUnsafePointer {p in
      stringValue = p.memory
 }

 return NSString(CString: stringValue)
iluvcapra
  • 9,436
  • 2
  • 30
  • 32
  • 1
    The `CMutablePointer` generic has a method called `withUnsafePointer` that yields an `UnsafePointer` to the block you give it (p here is an `UnsafePointer`). `UnsafePointer` has a property `memory` that is of type `T` and gives you access to the value the pointer points to. You can't save the `UnsafePointer` from the block, it's only good within the block, so you have to copy its value out there. – iluvcapra Jun 06 '14 at 14:55
  • Thank you! where I can find documents for Cstring/CMutablePointer? – galilio Jun 07 '14 at 06:45
  • I got this from the headers and reading here, the docs don't say anything about this at the moment... – iluvcapra Jun 07 '14 at 19:01
  • 1
    Apple give so little about how to integrate old C library to swift. – galilio Jun 09 '14 at 02:01
  • I think they'd rather you didn't, it defeats the purpose of having this awesome type-safe language if you're spending all your time copying bytes to and from UnsafePointers, I suspect they have a 3-year goal of killing with fire all the old C-isms. – iluvcapra Jun 09 '14 at 16:01
  • One more question, what's the relationship between swift and cocoa. can I consider cocoa as stdlib/socket/...etc for swift. – galilio Jun 10 '14 at 09:50
  • For a some more documentation take a look into "Using Swift with Cocoa and Objective-C" – Stephan Jun 29 '14 at 15:21
  • There is a chapter in "Using Swift with Cocoa and Objective-C" called "Interacting with C APIs", which gives a little bit of information, but absolutely no mention of withUnsafePointer or how to actually use the C APIs. Since large swaths of Apple's frameworks are C APIs, I believe we are all stuck with this hacky structure until they update them one day. Hopefully they document these processes more fully in the meantime. – jeremywhuff Jul 09 '14 at 19:14
0

You can do:

return NSString(UTF8String: name[0])
Howard Lovatt
  • 968
  • 1
  • 8
  • 15