Listing `void *` for an integer in C ++ is correct

I am dealing with some code that uses an external library in which you can pass values ​​for callbacks through a value void*.

Unfortunately, the previous person working on this code decided to just pass integers to these callbacks, dropping the integer to the void ( (void*)val) pointer .

Now I'm working on cleaning up this mess, and I'm trying to determine the "right" way to distinguish an integer from /. Unfortunately, fixing the use of void pointers is somewhat outside the scope of the refinement I can do here.

Right now, I'm doing two casts to convert from / to void pointer:

static_cast<int>(reinterpret_cast<intptr_t>(void_p))

and

reinterpret_cast<void *>(static_cast<intptr_t>(dat_val))

Since I am on a 64-bit machine, direct execution ( (int)void_p) results in an error:

error: cast from 'void*' to 'int' loses precision [-fpermissive]

The initial implementation worked with -fpermissive, but I am trying to get away from this for maintainability and error problems, so I am trying to do this “correctly”, for example. C ++ cast.

Casting is done directly in int ( static_cast<int>(void_p)) ( error: invalid static_cast from type 'void*' to type 'int'). My understanding reinterpret_castis that it basically just forces the compiler to treat the address of the value in question as a data type other than the type, without actually emitting any kind of machine code, so casting intdirectly to void*it would be a bad idea, because void*more than int(respectively 4/8 bytes).

, intptr_t , , void*, , , .

? , void?

+4
4

, intptr_t , , void*, , , .

, , . , , , , , typedef.

? , void?

, , .
, void* int intptr int, .

int int, . , .

+2

, , , void*, , void*.

; - , .

, Deduplicator, , , , , , . , :

void callbackFunction(void* dataPtr){
    int data = *(int*)dataPtr;
    /* DO SOMETHING WITH data */
    delete dataPtr;
}
void callLibraryFunction(int dataToPass){
    int* ptrToPass = new int(dataToPass);
    libraryFunction(ptrToPass,callbackFunction);
}

, , , .

+2

" , , , ?"

, , , void* .

, intptr_t , , void *, , , .

, reinterpret_cast<intptr_t>, , intptr_t, .


c API, , , , 1.

, , void* .


1) pthread_create() function >

+1

You have little choice but to use static and reinterpretation. Casting to int will result in a loss of precision, which will never be perfect. Explicit casting is always best avoided, because sooner or later what is cast can change, and then there will be no compiler warnings. But in this case, for obvious reasons, you have no choice. Or you?

You can change the callback definitions on your side to be intptr_t or long int, not void *, and then it should work and you don't have to do any keystrokes ...

0
source

All Articles