cast ref pointer

ag0aep6g anonymous at example.com
Thu Jan 18 16:14:18 UTC 2018


On 01/18/2018 04:25 PM, Luís Marques wrote:
> This works, obviously (i.e. it prints 42):
> 
>      void foo(ref int* a)
>      {
>          static int j = 42;
>          a = &j;
>      }
> 
>      void bar(int* ptr)
>      {
>          foo(ptr);
>          writeln(*ptr);
>      }
> 
>      void main()
>      {
>          int i = 7;
>          bar(&i);
>      }
> 
> Unfortunately, if bar for some reason receives a void* pointer (e.g. C 
> callback) this doesn't work:
> 
>      void bar(void* ptr)
>      {
>          foo(cast(int*) ptr); // error

You need a reinterpret-style cast here to get an lvalue:

     foo(* cast(int**) &ptr);

The result has the same type (int*), but it refers to the very same 
memory location as `&ptr` does. So it's not just a temporary value, and 
it can be passed in a `ref` parameter.

>          writeln(*cast(int*) *ptr);

You're dereferencing twice here. Do it only once, after casting:

     writeln(* cast(int*) ptr);

>      }
Alernatively, you can make a local variable for the casted pointer and 
use that instead of the `ptr`:

     int* casted_ptr = cast(int*) ptr;
     foo(casted_ptr);
     writeln(*casted_ptr);

That way, `ptr` itself won't be updated by `foo`, of course. But `ptr` 
isn't a `ref` parameter, so this only affects the insides of `bar` anyway.


More information about the Digitalmars-d-learn mailing list