calling a D function from C and C++ code

Steven Schveighoffer schveiguy at yahoo.com
Tue Aug 28 07:24:42 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.
>
> Thanks,
>
> -Bedros

I've done it with extern(C), but only in passing callback function pointers. 
For example, to catch signals, you can pass a function pointer to an 
extern(C) function to the sigaction system call.
e.g. (tango style):

import tango.stdc.posix.signal;
import tango.stdc.posix.unistd;
import tango.io.Stdout;

extern(C)
{
  void handlesignal(int sig)
  {
    Stdout("caught signal ")(sig).newline;
  }
}

int main(char[][] args)
{
  sigaction_t sa;
  sa.sa_handler = &handlesignal;
  sigaction(SIGINT, &sa, null);
  while(true)
  {
    sleep(10);
  }
  return 0;
}

However, I have not tried compiling C/C++ code that directly depends on D 
code.  I'm hoping not to have to deal with that ever :)

-Steve 





More information about the Digitalmars-d mailing list