avoid extra variable during void pointer cast

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 14 14:04:20 PDT 2017


On Sunday, 14 May 2017 at 20:18:24 UTC, Kevin Brogan wrote:
> 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.

First: Any decent compiler will optimize both the variable 
_state, as well as the variable _data out[1][2], this sounds like 
a classic case of *evil* early optimization. Trust your compiler 
to get it right; and if you're not sure, check the generated 
assembly.
Second: No, it is not possible, because an alias is a symbol that 
stands in for another type[3], not for an expression.

[1] https://godbolt.org/g/X4D02i
[2] https://godbolt.org/g/6i52Tt
[3] https://dlang.org/spec/declaration.html#alias


More information about the Digitalmars-d-learn mailing list