Last update January 30, 2008

Dcalled From C



Difference (last change) (no other diffs, normal page display)

Changed: 115c115
#gcc Cmain.c DmainDummy?.o Dfunc.o -o Cmain -lphobos -lpthread -lm
#gcc Cmain.c DmainDummy?.o Dfunc.o -o Ctest -lphobos -lpthread -lm

Changed: 121c121,122
TravelerHauptman
TravelerHauptman


Table of contents of this page
Calling D functions from C   
Example D function   
Problem and Solution   
Working C program   
Output   
Puzzle and /Discussion   
Another Example (under linux)   

Calling D functions from C    

This is possible although not emphasised with a heading - see the Interfacing page ( D 2.x, D 1.x) in the D language description. All that is needed is to declare the function as

extern (C)

Example D function    

/* Compute the greatest common divisor of positive integers */
extern(C) {
int  gcx (int x, int y)
 {
  int g;
  g = y;
  while (x > 0) {
    g = x;
    x = y % x;
    y = g;
  }
  return g;
 }
}

Problem and Solution    

The problem is that a C program which calls only this, does not link as there are undefined references _deh_beg and _deh_end . To resolve these it is necessary to define and call a D main program. This can be done in a routine callable from C.

extern(C) int call_main()
{
   return main();
}

int main()
{
   printf("Hello from main \n");
   return 0;
}

Working C program    

#include <stdio.h>
int call_main();
int gcx(int x, int y);

int main()
{
    printf("hello world\n");
    int x = call_main();
    printf("int y = gcx(5,50); calls a D function\n");
    int y = gcx(5,50);
    printf("The result is y = %d\n",y);
    return x;
}

Output    

hello world
Hello from main
int y = gcx(5,50); calls a D function
The result is y = 5

Puzzle and /Discussion    

The above also works with only the definition of the D main() routine and without the call. I am not clear as to whether that is just that this example is so simple. Does the D main() do some housekeeping which is needed? Should there be call to something else at exit, or has it been done when main() exited?

JohnFletcher

There is indeed some housekeeping going on in dmd/src/phobos/internal/dmain2.d
For some sample code see NG:digitalmars.com.D.gnu/1436

ThomasKühne

Another Example (under linux)    

Dmaindummy.d

int main(){return 0;}

Dfunc.d

import std.c.stdio;
extern (C) void dfunc()
{
  printf("\nMy code is easier to read and write!\n");
}

Cmain.c

#include <stdio.h>
extern dfunc();
int main()
{
  dfunc();
  printf("\nld likes my main() better than D's main()!\n");
  return 0;
}

Put it all together!

#dmd -c Dmaindummy.d Dfunc.d
#gcc Cmain.c DmainDummy.o Dfunc.o -o Ctest -lphobos -lpthread -lm
#./Ctest
My code is easier to read and write!
ld likes my main() better than D's main()!

TravelerHauptman


FrontPage | News | TestPage | MessageBoard | Search | Contributors | Folders | Index | Help | Preferences | Edit

Edit text of this page (date of last change: January 30, 2008 22:15 (diff))