Mecki Mecki - 3 months ago 31
Swift Question

Swift3: Converting raw pointer to Int (pointer itself being the int value, doesn't point anywhere!)

Consider the following code in C:

void someFunction ( int type, void * someData ) {
unsigned value = (int)someData;

I know this code looks a bit strange but this function is a callback function and the callback function must take a
void *
argument, as very often
is in fact a pointer to some memory structure (
would tell me which structure) but in that case it isn't. In that case it is really just an unsigned int value; not a pointer to such a value but the value itself. The caller really calls this function like this:

unsigned value = ...;
callbackFunction(type, (void *)value);

Yeah, that's stupid and ugly but I haven't written the code and I cannot change it either. I just have to implement the callback. And I would really love to do so in Swift (Swift 3). But in Swift, the callback has to look like this:

func someFunction ( _ type: Int, _ someData: UnsafeMutableRawPointer? ) -> Void

And my function is called just fine... but how do I get the numeric pointer value as I need the unsigned int value and pass it on to another function.


You can use Int(bitPattern:) to get the pointer value as an integer:

func someFunction ( _ type: Int, _ someData: UnsafeMutableRawPointer? ) -> Void {
    if let ptr = someData {
        let value = Int(bitPattern: ptr)