Pass D const pointer to opaque C library: Guarantees? Optimization-safe?

SimonN eiderdaus at gmail.com
Sat Dec 16 08:56:59 UTC 2017


Hi,

I'm calling a C library through a D wrapper. The situation is 
like this:

C library has:
     struct A      { ... };
     A* create_a() { ... }
     void foo(A*)  { ... }

D wrapper declares:
     extern (C) {
         struct A {}
         A* create_a();
         void foo(A*);
     }

My D usercode:
     const A* a = create_a();
     foo(cast(A*) a);

We know that const is transitive in D and the compiler may 
optimize around it. If we cast away const, it's our 
responsibility that, e.g., the optimized caching from const will 
not cause bugs.

The memory of the A is allocated by the C library. All the D code 
ever sees is a pointer, an opaque handle to the resource. How 
will the compiler optimizations behave around this:

Question 1. Is that cast still safe in usercode if foo(a) changes 
some internal values in *a that are undetectable through the C 
API?

Question 2. If yes, can the wrapper sanely declare foo(const A*) 
instead of foo(A*)?

My use case: My const-heavy D usercode calls Allegro 5, a C 
game/multimedia library without any const in its API, through the 
D bindings DAllegro5. I'm considering to make a PR implementing 
question 2. Github issue: 
https://github.com/SiegeLord/DAllegro5/issues/42

-- Simon


More information about the Digitalmars-d-learn mailing list