Amutha Priya
Amutha Priya

Reputation: 341

How to pass substring from Swift to C?

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.

Upvotes: 0

Views: 48

Answers (1)

Martin R
Martin R

Reputation: 539725

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.

Upvotes: 1

Related Questions