Qs about structs and their references WRT C functions and variables

Jarrett Billingsley kb3ctd2 at yahoo.com
Tue Jan 30 17:29:28 PST 2007


"Rick Mann" <rmann-d-lang at latencyzero.com> wrote in message 
news:epoqju$26f0$1 at digitaldaemon.com...
> I'm working on some C bindings, and I need to know a few things that 
> aren't clear from the spec.
>
> a) If a C function takes a pointer to a struct so that it can fill that 
> struct (return it), I've found I can write the parameter as "out MyStruct 
> outS", and things work as expected (I don't take the address of the 
> parameter I pass).

Right.  'out' implicitly passes the struct by reference, so if the struct 
parameter is a return value, then 'out' is the right way to go.  That it 
works with C libraries is something that I didn't know, and something very 
cool..

> If a function simply takes a struct as input, and therefore I leave off 
> any qualifier in the D parameter declaration (i.e., "MyStruct inS"), is 
> the struct still passed by reference? I assume so, but want to be sure.

No.  It's passed by value, just like if you were to write

void func(struct SomeStruct s);

in C.

> b) Some of the API's in C pass the entire struct (I question the wisdom of 
> this). How do I link to these?

If the struct is fairly small, passing the struct by value probably isn't 
that much of a performance loss (and might even be a gain, if it accesses 
the structs members often inside the function).  But if it were declared as

void func(struct SomeStruct s);

in C, then you declare it as

extern(C) void func(SomeStruct s);

in D.

> c) I need to declare a couple of extern structs. Can I just slap an 
> "extern (C)" on these and all will be well? The spec seems to indicate 
> that this is so, and it may be fine; I'm just looking for verification. 
> e.g.:
>
> struct
> ControlID
> {
> uint signature;
> int id;
> };
> typedef ControlID                       HIViewID;
> extern (C)
> const HIViewID kHIViewWindowContentID;
>
> TIA,
> Rick

Hmm.. if I remember correctly, those extern struct declarations have to be 
in a .d file which is _imported_ but never _compiled_.  So you'd have 
something like

importedstructs.d

struct ControlID
{
    uint signature;
    int id;
}

typedef ControlID HIViewID;
extern(C) const HIViewID kHIViewWindowContentID;

And then the rest of your program would have:

import importedstructs;

But you wouldn't put importedstructs.d on the command line when you compile 
your program. 




More information about the Digitalmars-d-learn mailing list