Extensions to types loaded from a C library

simendsjo simendsjo at gmail.com
Fri Dec 14 02:16:12 PST 2012


On Friday, 14 December 2012 at 09:30:50 UTC, Jeremy DeHaan wrote:
> I was playing with some code in the Derelict project(mainly the 
> SFML portion) and was wondering what would happen if I made 
> some changes.
>
> Here's an example of what I mean.
> In the C code, the struct sfVector2f is defined as such:
>
> typedef struct
> {
>     float x;
>     float y;
> } sfVector2f;
>
> The D version of this when loading the .dll into the 
> application would be like this:
>
> struct sfVector2f
> {
>     float x;
>     float y;
> }
>
> And to my understanding, defining this allows us to use this 
> structure in our calls to the C functions in the .dll. But then 
> I thought, "could I maybe make some things easier?" and 
> proceeded to experiment a bit. Right now I have the structure 
> looking like this:
>
> struct sfVector2f
> {
>     float x;
>     float y;
> 	
> 	this(float X, float Y)
> 	{
> 		x = X;
> 		y = Y;
> 	}
> }
>
> This compiles just fine, and I can even use the constructor to 
> create the object with seemingly no problems. But is this safe 
> to do? My gut tells me yes, but I would rather make sure before 
> I cause something to explode unknowingly!

As far as I know, this should be perfectly safe, and is exactly 
what derelict (and every other binder library) does.
If you try to add additional fields, it wont work though..

You might consider using alias this instead:
struct Vector2f {
   sfVector2f vec;
   this(float x, float y) {
     vec.x = x;
     vec.y = y;
   }
   alias vec this;
}

This way Vector2f is implicitly converted to sfVector2f whenever 
needed, and you can add additional fields to your struct.


More information about the Digitalmars-d-learn mailing list