我的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
}
工作得非常好!
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中,如何访问内存中的字符串?
答案 0 :(得分:0)
你可以使用UnsafePointers在Swift中进行指针运算:
let oldPointer = UnsafePointer<UInt8>()
let newPointer = oldPointer + 10
它创建10个字节的偏移量。
答案 1 :(得分:0)
你不需要alloc()
,只需要一个类型&#34;指向的变量
指向Int8&#34;的指针,类似于(Objective-)C代码:
var formats : UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = nil
let count = Int(enumDataFormat(&formats))
您只需使用下标符号即可访问第i个C字符串指针...
for i in 0 ..< count {
let formatString = formats[i]
...并将其转换为带
的Swift字符串 if let format = String.fromCString(formatString) {
println(format)
} else {
// Not a valid UTF-8 string.
}
}