calling a D function from C and C++ code
Bill Baxter
dnewsgroup at billbaxter.com
Sat Aug 25 23:50:52 PDT 2007
Bedros Hanounik wrote:
> I'm a lot interested in D recently, and have been reading the
> documentation the wiki, forums, etc. But I could not find a place
> where it explains how to call a D function from C and C++ code
>
> all the documentation...etc discusses how to bind an existing library
> to D code; which is the most common case, but how about building a
> brand new library written in D; can anyone write a C code (or C++) to
> interface this library in D.
Pretty easy conceptually, just make any functions you want to call from
C/C++ be "extern(C)", makeing sure you don't use any funky D-only
parameter types, and then write the equivalent C prototype in a header
file for the C/C++ code to use (and extern "C" it for C++).
In practice on Windows there are a few other issues in that DMD
generates libs that aren't compatible with MSVC or MinGW. The libs are
link-compatible with the output of the Digital Mars C/C++ compiler,
though (DMC), which you already have if you installed DMD. If you're
using GDC, I think you'll also be ok. MinGW generates MSVC-compatible
libs, so the MinGW version of GDC should be ok.
I'm not sure how to handle it if you want to use DMD on Windows and call
from something besides DMC (like MinGW or MSVC). I think in that case
your best bet is to create a DLL from the D code. From there you should
be able to use MSVC tools, MinGW tools or whatever to create an import
lib in the proper format for the C/C++ compiler you want to use.
This is something I've been meaning to try out myself but actually
haven't done it myself. I know for instance Kirk uses DLLs to link D
code into C/Python as a part of PyD.
Hope that helps.
--bb
More information about the Digitalmars-d
mailing list