Extensions to types loaded from a C library

Mike Parker aldacron at gmail.com
Fri Dec 14 04:36:34 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!

With D's UFCS syntax, there's really no need to modify Derelict 
directly to extend a C struct.

http://www.gamedev.net/blog/1140/entry-2254754-uniform-function-call-syntax-in-d/

Obviously, this technique won't work for constructors, but it 
should work for most any other method you'd like to add. And I 
don't see a need to add a constructor anyway except in very 
specific circumstances (i.e. you want a constructor with fewer or 
more params, or different types, than the number or type of 
struct fields). And even then it's only a convenience.


More information about the Digitalmars-d-learn mailing list