Reuse C memory for D struct?

Mike Parker aldacron at gmail.com
Thu Nov 21 17:19:17 PST 2013


On 11/22/2013 12:22 AM, Lemonfiend wrote:
> Hi!
>
> I'm wondering if it's possible to have a struct in D which uses the same
> pointer and memory as returned by the extern C function.
> This would allow me to manipulate and use the C struct directly in D code.

I'm trying to understand why you would want to this, but I just can't 
see a reason. Why not just define a struct in D that matches the C 
definition and then use the pointer directly?

Example:

// foo.h
typedef struct {
     int x;
} Foo;

extern Foo* newFoo( void );

// foo.d
struct Foo {
     int x;
}
extern( C ) Foo* newFoo();

auto f = newFoo();
writeln( f.x );

Of course, if Foo is an opaque struct on the C side, you'll be playing 
with fire if you define it in D and don't have control of the C library. 
In that case, you should make it opaque in D as well.


More information about the Digitalmars-d-learn mailing list