gpt4 book ai didi

objective-c - 将 (void *) 转换为 (SInt16 *) 到 Swift

转载 作者:搜寻专家 更新时间:2023-11-01 06:30:25 27 4
gpt4 key购买 nike

我正在尝试将以下内容从 Objective-C 转换为 Swift:

-(int)fillBuffer:(void *)buffer {
SInt16* p = (SInt16 *)buffer;

// ...

p[33] = 0
}

我开始明白 (void *) 映射到 UnsafeMutableRawPointer? Swift 中的类型。

但是,我缺少将其转换为可以执行下标操作的内容的步骤。

到目前为止,我得到了这个:

func fill(buffer: UnsafeMutableRawPointer!) -> Int {
buffer[33] = 0
}

寻求反馈和建议。提前致谢!

最佳答案

将 void 指针转换为类型化指针

SInt16* p = (SInt16 *)buffer;

在 Swift 中使用 assumingMemoryBound() 完成:

func fillBuffer(_ buffer: UnsafeMutableRawPointer) -> Int {
let p = buffer.assumingMemoryBound(to: Int16.self)
// ...
p[33] = 0
return 0
}

测试代码:

var i16Array = Array(repeating: Int16(99), count: 40)
print(i16Array[33]) // 99
_ = fillBuffer(&i16Array) // passes a pointer to the element storage to the function
print(i16Array[33]) // 0

关于objective-c - 将 (void *) 转换为 (SInt16 *) 到 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48221156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com