How to make D libraries callable from C?
Brad Roberts
braddr at puremagic.com
Mon Dec 18 11:05:43 PST 2006
Gregor Richards wrote:
> %u wrote:
>> Hello,
>> I am a D newbie and my company makes heavy use of C. I would like to
>> demonstrate that the D language can be beneficial much more than Java.
>> My question is: is it possible to make a library, that is callable
>> from C? I guess i would have to write the corresponding .h file for
>> inclusion, with possibly a C-wrapper around the D classes.
>> Thank you for helping.
>>
>> Alain
>
> All you need is to use extern (C) on those functions you want to be
> callable from C.
>
> D:
>
> extern (C) void doStuff(int withThis) { ... }
>
>
> C header:
> void doStuff(int);
>
> - Gregor Richards
There's more to it than that.
The D runtime will need to be initialized unless special care is taken
to avoid anything that's going to touch the GC or anything else that
requires initialization. (it's been a while since I looked at that part
of phobos/ares.
You'll have to be careful to keep the interfaces to mutually compatible
data types. D doesn't prevent you from writing something like:
extern (C) char[] someFunc(SomeClass a, SomeAlias b, SomeDelegate c)
Essentially all the extern C part does is drop the name mangling.
Don't let exceptions leak out of this D/C barrier.. C doesn't know
anything about exceptions. If instead of C you really meant C++, the
same still applies except with dmd on windows. Every other combination
of language/compiler/os is currently incompatible, though I'd love to
see this fixed.
There might be something else that needs to be handled as well, but
those are the things that come to mind quickly.
Later,
Brad
More information about the Digitalmars-d
mailing list