0

I'm interacting with a C++ library (with the header in C) which uses const char ** as an output parameter.

After executing a method in that library, the value I need is written in that variable, for example:

CustomMethod(const char **output)

CustomMethod(&output)

// Using the `output` here

Normally, in Swift it's possible to pass just a standard Swift String as a parameter and it will be transparently transformed into the const char * (Interacting with C Pointers - Swift Blog).

For example, I already use the following construct a lot with the same library:

// C
BasicMethod(const char *input)

// Swift
let string = "test"
BasicMethod(string)

However, when it comes to working with const char **, I couldn't just pass a pointer to the Swift String, as I'd expected:

// C
CustomMethod(const char **output)

// Swift
var output: String?
CustomMethod(&output)

Getting an error:

Cannot convert value of type 'UnsafeMutablePointer<String?>' to expected argument type 'UnsafeMutablePointer<UnsafePointer?>' (aka 'UnsafeMutablePointer<Optional<UnsafePointer>>')

The only way I could make it work is by manipulating the pointers directly:

// C
CustomMethod(const char **output)

// Swift
var output: UnsafePointer<CChar>?
CustomMethod(&output)
let stringValue = String(cString: json)

Is there any way to use the automatic Swift string to const char ** conversion, or does it only work with const char *?

1
  • 1
    To answer the question from the last paragraph - no, it's not possible to get automatic conversion, you'll have to write some Swift pointer code. Commented Jun 21, 2021 at 14:41

1 Answer 1

3

The bridged C function expects a mutable pointer to a CChar pointer, so you'll need to provide one, there's no automatic bridging here.

var characters: UnsafePointer<CChar>?
withUnsafeMutablePointer(to: &characters) {
    CustomMethod($0)
}

if let characters = characters {
    let receivedString = String(cString: characters)
    print(receivedString)
}

Same code, but in a more FP manner:

var characters: UnsafePointer<CChar>?
withUnsafeMutablePointer(to: &characters, CustomMethod)

var receivedString = characters.map(String.init)
print(receivedString)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your clarification! It seems that I've missed withUnsafeMutablePointer method, which is important according to the developer documentation: developer.apple.com/documentation/swift/…

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.