LoginSignup
0
0

More than 5 years have passed since last update.

C の char **hoge のために、Swift で UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>! を作る

Last updated at Posted at 2019-02-21

Swift の String を UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>! にする

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) {
    // いろいろ
}

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

C の UnsafeMutablePointer<Int8>? を Swift の String にする

sample.swift
let foo = get_foo()
let result = String(cString: foo!) // TODO: nil 安全にすべき
print(result)
sample.c
char* get_foo() {
    // return うんたら
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0