长度转换的UnsafePointer到斯威夫特数组类型 [英] Converting an UnsafePointer with length to a Swift Array type

查看:208
本文介绍了长度转换的UnsafePointer到斯威夫特数组类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找实现斯威夫特合理ç互操作最简单的方法,而我目前的块转换成一个 UnsafePointer< INT8> (这是一个为const char * ),到 [INT8] 阵列。

I'm looking for the simplest ways to achieve reasonable C interoperability in Swift, and my current block is converting an UnsafePointer<Int8> (which was a const char *), into an [Int8] array.

目前,我有一个天真的算法,可以采取 UnsafePointer 和字节数和元素,它的元素转换为数组:

Currently, I have a naïve algorithm that can take an UnsafePointer and a number of bytes and converts it to an array, element by element:

func convert(length: Int, data: UnsafePointer<Int8>) {

    let buffer = UnsafeBufferPointer(start: data, count: length);
    var arr: [Int8] = [Int8]()
    for (var i = 0; i < length; i++) {
        arr.append(buffer[i])
    }
}

循环本身可以通过使用 arr.reserveCapacity(长),但这并不删除循环本身的问题有待加快。

The loop itself can be sped up by using arr.reserveCapacity(length), however that does not remove the issue of the loop itself.

我知道的这太问题其中包括如何 UnsafePointer&LT转换; INT8&GT; 字符串,但字符串是完全不同的野兽 [T] 。是否有复制长度字节从 UnsafePointer℃的方便迅捷的方式; T&GT; [T] ?我想preFER纯斯威夫特方法,而不通过的NSData 或相似。如果上面的算法是真的做到这一点的唯一途径,我很高兴地坚持这一点。

I'm aware of this SO question which covers how to convert UnsafePointer<Int8>to String, however String is a different beast entirely to [T]. Is there a convenient Swift way of copying length bytes from an UnsafePointer<T> into a [T]? I'd prefer pure Swift methods, without passing through NSData or similar. If the above algorithm is really the only way to do it, I'm happy to stick with that.

推荐答案

您可以简单地初始化斯威夫特阵列 UnsafeBufferPointer

You can simply initialize a Swift Array from an UnsafeBufferPointer:

func convert(length: Int, data: UnsafePointer<Int8>) -> [Int8] {

    let buffer = UnsafeBufferPointer(start: data, count: length);
    return Array(buffer)
}

这将创建所需的大小,并将数据复制的数组。

This creates an array of the needed size and copies the data.

或者作为通用功能:

func convert<T>(count: Int, data: UnsafePointer<T>) -> [T] {

    let buffer = UnsafeBufferPointer(start: data, count: count);
    return Array(buffer) 
}

其中,长度项目的该指针指向。

如果你有一个 UINT8 指针,但要创建从 [T] 阵列
所指向的数据,那么这是一个可能的解决方案:

If you have a UInt8 pointer but want to create an [T] array from the pointed-to data, then this is a possible solution:

func convert<T>(length: Int, data: UnsafePointer<UInt8>, _: T.Type) -> [T] {

    let buffer = UnsafeBufferPointer<T>(start: UnsafePointer(data), count: length/strideof(T));
    return Array(buffer) 
}

其中,长度现在是多少的字节的。例如:

where length now is the number of bytes. Example:

let arr  = convert(12, data: ptr, Float.self)

将从12个字节创建3 浮动组成的数组指向 PTR

这篇关于长度转换的UnsafePointer到斯威夫特数组类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆