0

I have the variable with the value "7438754876*567".I have got this from string as substring.I want to pass this value to c function.

void getRechargePinFromDestination(char* rechargeNumber)
{
    setRechargeValue(rechargeNumber);
}

As I have declared as char, swift takes it as a Int8.How can I pass this value.Anyone please help me.Thanks in advance.

2
  • Does the C function modify the string? Or can you declare it as void getRechargePinFromDestination(const char * rechargeNumber) ?
    – Martin R
    Jul 20, 2020 at 11:47
  • Cannot convert value of type 'Substring' to expected argument type 'UnsafePointer<Int8>?' ........ This is my prblm... Jul 20, 2020 at 11:50

1 Answer 1

1

If the C function does not mutate the passed string then you should declare the argument as a const char*:

void getRechargePinFromDestination(const char* rechargeNumber)
{
     // ...
}

Now you can pass Swift substrings by converting them to a String first (which is automatically converted to a temporary C string):

getRechargePinFromDestination(String(subString))

or with

subString.withCString { getRechargePinFromDestination($0) }

In either case, the C function is called with a pointer to a temporary C string representation, which is only valid during the function call.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.