This is an old revision of the document!


Lab 07: C/C++ Interoperability and Tooling

Interfacing to C

Calling C functions from D

C functions can be called directly from D. There is no need for wrapper functions, argument swizzling, and the C functions do not need to be put into a separate DLL. The C function must be declared and given a calling convention, most likely the “C” calling convention, for example:

extern (C) int strcmp(const char* string1, const char* string2);

and then it can be called within D code in the obvious way:

import std.string;
int myDfunction(char[] s)
{
    return strcmp(std.string.toStringz(s), "foo");
}

Calling D functions from C

For D functions to be able to be called from a C context, they should be annotated with the extern(C) attribute:

// test.d
extern (C) int average(int a, int b) { return (a+b)/2; }  

On the C side, the function signature must be provided:

<code C> main.c int average(int a, int b); void main() { int a = average(5, 9); printf(”%d\n”, a); prints 7; }

Compilation of the sources is done in the following manner:

<code bash> dmd -c test.d gcc -o main.o -c main.c gcc test.o main.o <code>

Compiling the D and C code to object modules and then linking them into an executable is all that needs to be done. For this to work it is imperative that the label (the function name) is exactly the same on both D and C sides; also both sides need to respect the same calling convention. extern (C) instructs the compiler to mangle the name of the function according to the rules of the C languages; the D calling convention is the same as the C one.

dss/laboratoare/07.1562155006.txt.gz · Last modified: 2019/07/03 14:56 by razvan.nitu1305
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0