avoid extra variable during void pointer cast

Kevin Brogan via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 14 13:18:24 PDT 2017


I have a piece of code that takes a callback function.

The callback has the signature void callback(void* state, void* 
data)

There are several of these functions. All of them use state and 
data as differing types.

As an example, let's look at one that uses both of them as int*.

addInt(void* state, void* data)
{
     *cast(int*)state += *cast(int*)data;
}

Is it not possible to specify the cast as an alias so that I can 
declare the cast once at the beginning of the function?

Something like this?

addInt(void* state, void* data)
{
     alias _state = cast(int*)state; // Error: basic type 
expected, not cast
     alias _data = cast(int*)data; // Error: basic type expected, 
not cast

     *_state += *_data;
}

I can always do this:

addInt(void* state, void* data)
{
     int* _state = cast(int*)state;
     int* _data = cast(int*)data;

     *_state += *_data;
}

But I don't want to create a new variable and assign it everytime 
I call the function. The examples I'm using are contrived, but in 
the c code I am porting this from, the callback gets called 
thousands of times a second, every optimization matters, and the 
variables are used many times per function. I don't want to 
riddle the code with casts if i can avoid it and I don't want to 
create and destroy useless proxy variables every time the 
function is called.


More information about the Digitalmars-d-learn mailing list