1

I have some code to convert from Obj C to Swift, which involves strncpy.

The original Obj C code:

const char * c_amount = [[NSString stringWithFormat:@"%08d", (int)([amount floatValue])] UTF8String];
strncpy(request.amount, c_amount, (unsigned int)sizeof(request.amount));

What I've tried on Swift:

let c_amount = String(format: "%08d", Int(CFloat(amount))).utf8
strncpy(request.amount, c_amount, UInt(sizeof(request.amount)))

But this gives me error:

Cannot convert value of type '(Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)' to expected argument type 'UnsafeMutablePointer<Int8>'

I don't actually understand how to fix the error at all, as I rarely working with pointer on Swift. Can somebody help?

Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124

2 Answers2

1
var c_amount = someFunctionReturningCChar()

let name = withUnsafePointer(c_amount) {
    String.fromCString(UnsafePointer($0))!
}

This assumes that the bytes in c_amount are a valid NUL-terminated UTF-8 sequence.

Syed Qamar Abbas
  • 3,637
  • 1
  • 28
  • 52
  • Awesome for the `fromCString` and `withUnsafePointer` function! I guess I need to know more behind the hood about these two functions first. Let me try it! Thanks! – Chen Li Yong Nov 02 '16 at 03:58
1

I really, really, really recommend that you figure out what that code is actually doing, instead of trying to call strncpy. strncpy is dangerous. Not just dangerous, but DANGEROUS. If I saw strncpy in a code review (which isn't going to happen except may be on the first of April), that code would be rejected outright. Not a chance that it will be accepted.

Change request.amount to String and be done with it.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • I need to port some obj C code into a new swift app. The original framework, which I can't see the source code or modify it, only accept variables that was made using something like this. I have used swift equivalent to produce similar variables that's not pure C like this, but it didn't work when passed into the framework's function, unless I also want to build the framework too from scratch, which will not happen. This is an enterprise application, working with a custom bluetooth device, which won't go into apple store. – Chen Li Yong Nov 02 '16 at 03:56