1

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!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Been here for years and just signed up to ask this as it was really a tough nut to crack. Can't believe my first question got answered so quickly and with sound success! Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.