How to access unexported struct fields

If the struct is addressable, you can use unsafe.Pointer to access the field (read or write) it, like this: rs := reflect.ValueOf(&MyStruct).Elem() rf := rs.Field(n) // rf can’t be read or set. rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem() // Now rf can be read and set. See full example on the playground. This use of unsafe.Pointer is … Read more

Converting an UnsafePointer with length to a Swift Array type

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. Or as a generic function: func convert<T>(count: Int, data: UnsafePointer<T>) -> [T] { let buffer … Read more

Warning: Initialization of ‘UnsafeBufferPointer’ results in a dangling buffer pointer

I also met these annoying warnings. var str = “aaaaabbbbbccccc” var num1 = 1 var num2 = 22 var data = Data() // Initialization of ‘UnsafeBufferPointer<String>’ results in a dangling buffer pointer data.append(UnsafeBufferPointer(start: &str, count: 1)) // Initialization of ‘UnsafeBufferPointer<Int>’ results in a dangling buffer pointer data.append(UnsafeBufferPointer(start: &num1, count: 1)) // Initialization of ‘UnsafeBufferPointer<Int>’ results … Read more

How to cast self to UnsafeMutablePointer type in swift

An object pointer (i.e. an instance of a reference type) can be converted to a UnsafePointer<Void> (the Swift mapping of const void *, UnsafeRawPointer in Swift 3) and back. In Objective-C you would write void *voidPtr = (__bridge void*)self; // MyType *mySelf = (__bridge MyType *)voidPtr; (See 3.2.4 Bridged casts in the Clang ARC documentation … Read more

Swift 5.0: ‘withUnsafeBytes’ is deprecated: use `withUnsafeBytes(…)

In Swift 5 the withUnsafeBytes() method of Data calls the closure with an (untyped) UnsafeRawBufferPointer, and you can load() the value from the raw memory: let value = data.withUnsafeBytes { $0.load(as: UInt32.self) } (compare How to use Data.withUnsafeBytes in a well-defined manner? in the Swift forum). Note that this requires that the memory is aligned … Read more

Swift 3 UnsafePointer($0) no longer compile in Xcode 8 beta 6

From the Release Notes of Xcode 8 beta 6: An Unsafe[Mutable]RawPointer type has been introduced, replacing Unsafe[Mutable]Pointer<Void>. Conversion from UnsafePointer<T> to UnsafePointer<U> has been disallowed. Unsafe[Mutable]RawPointer provides an API for untyped memory access, and an API for binding memory to a type. Binding memory allows for safe conversion between pointer types. See bindMemory(to:capacity:), assumingMemoryBound(to:), and … Read more

tech