Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift define double pointer for struct defined in c

I have a library which contains this function:

void create_pointer(Pointer **pointer);

It takes a pointer's pointer and allocates memory for it. in c, I can do it like this

Pointer *pointer;
create_pointer(&pointer);

then I have a pointer's instance.

But now I want to use this function in Swift. How?

I have no details about Pointer, I only know it's a struct, defined like this

typedef struct Pointer Pointer;
like image 535
galilio Avatar asked Jun 06 '14 01:06

galilio


1 Answers

Let's start with a C example

typedef struct {
    NSUInteger someNumber;
} SomeStruct;

void create_some_struct(SomeStruct **someStruct) {
    *someStruct = malloc(sizeof(SomeStruct));
    (*someStruct)->someNumber = 20;
}

In C, you would use it like this:

//pointer to our struct, initially empty
SomeStruct *s = NULL;  

//calling the function
create_some_struct(&s);

In Swift:

//declaring a pointer is simple
var s: UnsafePointer<SomeStruct> = UnsafePointer<SomeStruct>.null()

//well, this seems to be almost the same thing :)
create_some_struct(&s)

println("Number: \(s.memory.someNumber)"); //prints 20

Edit:

If your pointer is an opaque type (e.g. void *), you have to use

var pointer: COpaquePointer = COpaquePointer.null()

Note that Swift is not designed to interact with C code easily. C code is mostly unsafe and Swift is designed for safety, that's why the Swift code is a bit complicated to write. Obj-C wrappers for C libraries make the task much easier.

like image 63
Sulthan Avatar answered Nov 09 '22 05:11

Sulthan