[swift-users] C Pointers and Memory

Bryan Chan bryanpkc at gmail.com
Sat Jul 30 12:51:04 CDT 2016


Personally I like swiftdoc.org as a reference:

http://swiftdoc.org/v3.0/type/UnsafeMutablePointer/

Click on the initializers and function names to read the description of
what each of them does.

You can use a UnsafeMutableBufferPointer to help initialize your memory
(which you have to allocate first):

var memory = UnsafeMutablePointer<Int8>(allocatingCapacity: 4)
var buf = UnsafeMutableBufferPointer<Int8>(start: memory, count: 4)
for i in 0...3 {
    buf[i] = Int8(0x10 * (i + 1)) // [ 16, 32, 48, 64 ]
}
CFunctionThatTakesACharPointer(memory, 4)

--
Bryan Chan

On Fri, Jul 29, 2016 at 11:40 PM, Chris McIntyre via swift-users <
swift-users at swift.org> wrote:

> Another problem. I have a specific byte pattern I want to create. For
> arguments sake, lets call it 0x123ABC, and I have it as an Int. I want to
> access the individual bytes (i.e. 12, 3A, BC).
>
> The struct reference for UnsafePointer<T> doesn’t talk much about
> initializing it. Most of the initializers take a pointer. I tried the
> init(_ bitPattern:) initializer, and was able to create a pointer, but it
> seemed to point to the address 0x123ABC rather than the address *of*
> 0x123ABC. I tried creating a buffer with malloc, and it gives me an
> UnsafeMutablePointer  but now I can’t figure out how to copy my bytes to
> this buffer.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160730/339b2824/attachment.html>


More information about the swift-users mailing list