正在将swift字符串复制到固定大小的字符[][]
我有一个这样的C结构正在将swift字符串复制到固定大小的字符[][],swift,macos,Swift,Macos,我有一个这样的C结构 struct someStruct { char path[10][MAXPATHLEN]; }; 我想将Swift字符串列表复制到char[10][]数组中 对我来说,在Swift中处理c二维字符数组是非常有挑战性的。有人能分享一些可以与Swift 5一起使用的代码吗?谢谢 C数组作为元组导入Swift。这里我们有一个二维C数组,它在Swift中成为嵌套元组: public struct someStruct { public var path: (
struct someStruct {
char path[10][MAXPATHLEN];
};
我想将Swift字符串列表复制到char[10][]数组中
对我来说,在Swift中处理c二维字符数组是非常有挑战性的。有人能分享一些可以与Swift 5一起使用的代码吗?谢谢 C数组作为元组导入Swift。这里我们有一个二维C数组,它在Swift中成为嵌套元组:
public struct someStruct {
public var path: (
(Int8, ..., Int8),
(Int8, ..., Int8),
...
(Int8, ..., Int8)
)
}
据我所知,没有真正“好”的解决方案,但利用Swift保留了导入的C结构()的内存布局这一事实,可以通过一些指针魔术来实现这一目标:
var s = someStruct()
let totalSize = MemoryLayout.size(ofValue: s.path)
let itemSize = MemoryLayout.size(ofValue: s.path.0)
let numItems = totalSize / itemSize
withUnsafeMutablePointer(to: &s.path) {
$0.withMemoryRebound(to: Int8.self, capacity: totalSize) { ptr in
for i in 0..<numItems {
let itemPtr = ptr + i * itemSize
strlcpy(itemPtr, "String \(i)", itemSize)
}
print(ptr)
}
}
var s=someStruct()
让totalSize=MemoryLayout.size(of值:s.path)
让itemSize=MemoryLayout.size(of值:s.path.0)
设numItems=totalSize/itemSize
WithUnsafemutable指针(指向:&s.path){
$0.withMemoryRebound(to:Int8.self,容量:totalSize){ptr in
对于0..中的i,我强烈建议您使用一些辅助方法
示例:
/* writes str to someStruct instance at index */
void writePathToStruct(struct someStruct* s, size_t index, const char* str) {
assert(index < 10 && "Specified index is out of bounds");
strcpy(s->path[index], str);
}
根据设计,元组不能通过变量索引访问。因此,静态读取可以在没有辅助函数的情况下完成
let pathRead = withUnsafeBytes(of: &someStructInstance.path.3) { pointer -> String? in
return String(cString: pointer.baseAddress!.assumingMemoryBound(to: CChar.self), encoding: encoding)
}
print(pathRead ?? "<Empty path>")
非常感谢你的绝妙建议。它真的救了我的命!
let pathRead = withUnsafeBytes(of: &someStructInstance.path.3) { pointer -> String? in
return String(cString: pointer.baseAddress!.assumingMemoryBound(to: CChar.self), encoding: encoding)
}
print(pathRead ?? "<Empty path>")
const char* readPathFromStruct(const struct someStruct* s, size_t index) {
assert(index < 10 && "Specified index is out of bounds");
return s->path[index];
}
pathRead = withUnsafePointer(to: &someStructInstance) { pointer -> String? in
return String(cString: readPathFromStruct(pointer, 3), encoding: encoding)
}