Create UnsafeMutablePointer <UnsafeMutablePointer <Int8>?>! In Swift for C char ** hoge

Set Swift String to UnsafeMutablePointer \ <UnsafeMutablePointer \ ?>!

sample.swift


import Foundation

let options = ["-m" : 2, "-n" : 3]

var args : [String] = []
for (option_name, value) in options {
    args.append(contentsOf: [option_name, value])
}
var cargs: [UnsafeMutablePointer<Int8>?] = args.map { strdup($0) }
initialize(Int32(args.count), &cargs)
for ptr in cargs { free(ptr) }

sample.c


void initialize(int argc, char **argv) {
    //various
}

See: https://developer.apple.com/documentation/swift/unsafemutablepointer

Make C UnsafeMutablePointer \ ? A Swift String

sample.swift


let foo = get_foo()
let result = String(cString: foo!) // TODO:nil should be safe
print(result)

sample.c


char* get_foo() {
    //return
}

Recommended Posts

Create UnsafeMutablePointer <UnsafeMutablePointer <Int8>?>! In Swift for C char ** hoge
Handle C char ** well in Swift
Pass C ++ char * to Swift
[Swift] Create UIButton class in code
Create Master Detail in Swift UI
Create an HTML/XML generator in Swift (dynamicMemberLookup)
Introducing C ++ characters and strings for Swift programmers
Create a tool for name identification in Salesforce
C macros for watchOS and Swift API Availability
C macros for tvOS and Swift API Availability