【问题标题】:Swift | Get pointer of c char array inside struct斯威夫特 |获取结构内c char数组的指针
【发布时间】:2019-07-20 05:36:33
【问题描述】:

我正在尝试将一些旧的 ObjC 代码转换为 Swift,我在 Swift 上没有做太多关于指针的事情。

ObjC/C 原代码:

unsigned char myId[6];
memcpy(myId, packet.header->m1, 6);

原始 C 结构:

typedef struct {
    unsigned char m1[6];
    unsigned char m2[6];
} __attribute__((__packed__)) HeaderStruct;

我尝试过的 Swift 代码,不工作:

var myId = [CUnsignedChar](repeating: 0, count: 6)
var headerStruct: UnsafePointer<HeaderStruct> = packet!.header()
memcpy(&myId, headerStruct.pointee.m1, 6)

关于headerStruct.pointee.m1的错误

无法转换类型 '(UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)' 到预期的参数类型'UnsafeRawPointer?'

我假设我需要基地址 (headerStruct) 并添加 m1 的偏移量,但我该怎么做呢?

【问题讨论】:

标签: c objective-c swift


【解决方案1】:

C 数组作为元组导入 Swift。但是内存布局被保留了,因此您可以获得指向存储元组的指针并将其“绑定”到指向UInt8 值的指针:

let myId = withUnsafeBytes(of: headerStruct.pointee.m1) {
    Array($0.bindMemory(to: UInt8.self))
}

【讨论】:

  • 我认为它可以工作(耶!,谢谢你),但 memcpy 也不能工作吗?
  • 那就是withUnsafePointer(to: headerStruct.pointee.m1) { memcpy(&amp;myId, $0, 6) }
猜你喜欢
  • 2018-01-04
  • 1970-01-01
  • 2017-07-22
  • 2017-03-24
  • 2020-07-31
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
相关资源
最近更新 更多