我有一个c API如下所示:

int enumDataFormat(char ***SampleNames);

银行代码:
var formats =  UnsafeMutablePointer<UnsafeMutablePointer<Int8>>.alloc(1)
let count = enumDataFormat(&formats)
for index in 0..<count {
    //Question in here: I don't known how to access memory in Swift
}

目标C代码:
它工作得很好!
char **formats;
int count = enumDataFormat(&formats);
if (count > 0) {
    for (int i = 0; i < count; i++) {

        //obtain the string from memory
        char *formatString = *(formats + i);
        NSLog(@"%s", formatString);
    }
}

问:在Swift中,如何访问内存中的字符串?

最佳答案

您不需要alloc(),只需要一个“指针指向”类型的变量
指向Int8“的指针,类似于(Objective-)C代码:

var formats : UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = nil
let count = Int(enumDataFormat(&formats))

你可以用下标符号访问第i个C字符串指针。。。
for i in 0 ..< count {

    let formatString = formats[i]

... 把它转换成一个快速的字符串
    if let format = String.fromCString(formatString) {
        println(format)
    } else {
        // Not a valid UTF-8 string.
    }
}

08-16 13:14