drummingdemon
drummingdemon

Reputation: 45

How can I get the values of a C pointer to a Swift struct?

I'm building a Swift wrapper / interface for a pre-compiled C library that is shipped with its' own header file. I have every function working except for the following. The library reads given parts of the loaded file's header. I have a struct that looks like this:

typedef struct {
    DWORD width;
    DWORD height;
    DWORD length;
    const void *data;
} T_PICTURE;

and a function in said library that returns a UnsafePointer<Int8> pointer when it is given a readable file (a part of a specific metadata, a picture to be exact).

My question is: how am I able to assign the data at the given memory location to a struct of that kind?

I would like to assign that space in memory to a struct of that kind, but so far I have been unable to.

I'm positive that because I'm relatively new to programming I'm missing something crucial or at the very least I don't see something fundamental. Been looking around for days now before deciding to ask, thank you in advance!

Upvotes: 1

Views: 345

Answers (1)

Martin R
Martin R

Reputation: 539705

If I understand your question correctly then you have a
ptr: UnsafePointer<Int8> which points to a memory location containing a T_PICTURE structure.

In Swift 2 you can simply "recast" the pointer and deference it. This would copy the data pointed-to by ptr to the picture variable of type T_PICTURE:

let picture = UnsafePointer<T_PICTURE>(ptr).memory

In Swift 3 you'll have to "rebind" the pointer:

let picture = ptr.withMemoryRebound(to: T_PICTURE.self, capacity: 1) {
    $0.pointee
}

See UnsafeRawPointer Migration for more information about the new pointer conversion APIs.

Upvotes: 2

Related Questions