Using D libs in C

Steven Schveighoffer schveiguy at yahoo.com
Mon Feb 7 08:41:10 PST 2011


On Mon, 07 Feb 2011 10:28:41 -0500, GreatEmerald <pastas4 at gmail.com> wrote:

> Everything is right from what I can tell. This is the code I use for the  
> D part:
>
> module dpart;
> import std.c.stdio;
>
> extern(C):
>
>     shared int ResultD;
>
>     int Process(int Value)
>     {
>         printf("You have sent the value: %d\n", Value);
>         ResultD = (Value % 5);
>         return ResultD;
>     }
>
> And the C part:
>
> #include <stdio.h>
> extern int ResultD;
> int Process(int Value);
>
> int main()
> {
> 	printf("Sending 3...\n");
> 	Process(3);
> 	printf("The result is %d\n", ResultD);
> 	getchar();
> 	return 0;
> }
>
> This is pretty much the same thing as in the Windows version, just with  
> scanf()
> omitted.
>
> Jacob, in Windows I am required to explicitly tell DMD to compile  
> phobos.lib, but
> not in Linux. Quite odd.

The issue is that you are not calling the D runtime initialization code.   
This is required in order to get D working properly.  See the C main  
function in druntime here:

https://github.com/D-Programming-Language/druntime/blob/master/src/rt/dmain2.d#L335

Basically, you are going to have to duplicate the runtime startup code.   
I'm not sure it will work properly.  People typically run main from D and  
call their C functions from there.  This is also certainly an option.

The errors you are getting are link errors.  I'm guessing that maybe  
because you aren't calling the d runtime, the linker is opimizing out the  
deh code early on, but then needs it again later?  Not sure.

-Steve


More information about the Digitalmars-d-learn mailing list