Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift C void* and void** pointers in latest betas (4)

Tags:

c

swift

In previous betas, I was able to pass a pointer to anything to C doing something like this

var aString : NSString = "This is a string" // create an NSString
var anUnmanaged = Unmanaged.passUnretained(aString) // take an unmanaged pointer
var opaque : COpaquePointer = anUnmanaged.toOpaque() // convert it to a COpaquePointer
var mut : CMutablePointer = &opaque // this is a CMutablePointer
doSomething(mut) // pass the pointer to an helper function written in C

With the C function like this:

void doSomething(void ** ptr)
{
   // do something with the pointer, change it and make it point to another nsstring for example
}

Now, (for sure in Beta4, maybe even in Beta3) the syntax translated from C to Swift has changed

Before, the doSomething function was expecting a CMutablePointer (that now has been removed from Swift) Now, it expects a:

UnsafePointer<UnsafePointer<()>>

() is a typealias to Void

So, syntactically talking is more clear. However, Now I can't understand how to take the void** pointer of any object like I was doing in previous betas.

Any suggestion?

like image 430
LombaX Avatar asked Jul 29 '14 09:07

LombaX


People also ask

What is void * in C?

The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

Can you free a void * in C?

Not only is it OK to free() a void * value, by definition, all free() ever sees is a void * , so technically, everything freed in C is void * :-) @Daniel - If you ask me, it should be struct foo *p = malloc(sizeof *p)); but what do I know?

What is void * ptr C++?

A void pointer in C++ is a special pointer that can point to objects of any data type. In other words, a void pointer is a general purpose pointer that can store the address of any data type, and it can be typecasted to any type. A void pointer is not associated with any particular data type.


1 Answers

This worked for me:

var str = "Hello, playground"
var p: UnsafePointer<Void> = unsafeAddressOf(str)
like image 198
sononum Avatar answered Sep 30 '22 22:09

sononum