Как один байт доступа (или Int16 годов, поплавки и т.д.) из памяти, на которую указывает на UnsafeMutableRawPointer (новый в Swift 3) передал в Swift функции на C API (Core Audio и др.)Р >
Как получить байты из UnsafeMutableRawPointer?
Ответ 1
load<T>
считывает необработанные байты из памяти и строит значение типа T
:
let ptr = ... // Unsafe[Mutable]RawPointer
let i16 = ptr.load(as: UInt16.self)
необязательно при смещении байта:
let i16 = ptr.load(fromByteOffset: 4, as: UInt16.self)
Существует также assumingMemoryBound()
, который преобразуется из a Unsafe[Mutable]RawPointer
в Unsafe[Mutable]Pointer<T>
, считая, что указательная память содержит значение типа T:
let i16 = ptr.assumingMemoryBound(to: UInt16.self).pointee
Для массива значений вы можете создать "указатель буфера":
let i16bufptr = UnsafeBufferPointer(start: ptr.assumingMemoryBound(to: UInt16.self), count: count)
Указатель буфера может быть уже достаточным для вашей цели, он подлежит индексированию и может быть перечислено аналогично массиву. При необходимости создайте массив из указателя буфера:
let i16array = Array(i16bufptr)
Как сказал @Hamish, дополнительную информацию и подробную информацию можно найти на
Ответ 2
Создайте объект Данные.
init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Data.Deallocator)
Один из важных способов, отсутствующих в других ответах здесь, - инициализировать объект Data с помощью UnsafeMutableRawPointer. Затем объект данных можно использовать для других вычислений.
public func base64(quality: Int32 = 67) -> String? {
var size: Int32 = 0
if let image = gdImageJpegPtr(internalImage, &size, quality) {
// gdImageJpegPtr returns an UnsafeMutableRawPointer that is converted to a Data object
let d = Data(bytesNoCopy: image, count: Int(size), deallocator: .none)
return d.base64EncodedString()
}
return nil
}
Ответ 3
Ниже приведена документация api для Unsafe [Mutable] RawPointer для преобразования T/Unsafe [MutablePointer]:
/// Binds the allocated memory to type `T` and returns an
/// `UnsafePointer<T>` to the bound memory at `self`.
///
/// - Precondition: The memory is uninitialized.
/// - Postcondition: The memory is bound to 'T' starting at `self` continuing
/// through `self` + `count` * `MemoryLayout<T>.stride`
/// - Warning: Binding memory to a type is potentially undefined if the
/// memory is ever accessed as an unrelated type.
public func bindMemory<T>(to type: T.Type, capacity count: Int) -> UnsafePointer<T>
/// Converts from an `UnsafeRawPointer` to UnsafePointer<T> given that
/// the region of memory starting at `self` is already bound to type `T`.
///
/// - Precondition: The memory is bound to 'T' starting at `self` for some
/// unspecified capacity.
///
/// - Warning: Accessing memory via the returned pointer is undefined if the
/// if the memory has not been bound to `T`.
public func assumingMemoryBound<T>(to: T.Type) -> UnsafePointer<T>
/// Reads raw bytes from memory at `self + offset` and constructs a
/// value of type `T`.
///
/// - Precondition: The underlying pointer plus `offset` is properly
/// aligned for accessing `T`.
///
/// - Precondition: The memory is initialized to a value of some type, `U`,
/// such that `T` is layout compatible with `U`.
public func load<T>(fromByteOffset offset: Int = default, as type: T.Type) -> T
а затем от Unsafe[MutablePointer]<T>
до T
можно преобразовать с помощью
pointee
и move
apis
/// Accesses the `Pointee` instance referenced by `self`.
///
/// - Precondition: the pointee has been initialized with an instance of
/// type `Pointee`.
public var pointee: Pointee { get }
/// Retrieves the `pointee`, returning the referenced memory to an
/// uninitialized state.
///
/// Equivalent to `{ defer { deinitialize() }; return pointee }()`, but
/// more efficient.
///
/// - Precondition: The pointee is initialized.
///
/// - Postcondition: The memory is uninitialized.
public func move() -> Pointee