Interfacing to C, What Are The Risks?

Asked By 10 points N/A Posted on -
qa-featured

My client needs the codes I created in D to be interfaced in C. I'm a bit anxious on what can it do to my D code. If anybody here have successfully interfaced C please let me know of the risks like What are some things I should do? Are there data compatibility issues? Should I access C globals?

SHARE
Answered By 0 points N/A #108188

Interfacing to C, What Are The Risks?

qa-featured

Hello Owen, for converting your codes to C some changes will be made, but there is no risk in it. D is designed to be fit easily with a C compiler. D does not have its own VM. So it relies on the target environment's C runtime library. It won’t make any sense if you attempt to port to D or write D wrappers for the vast array of C APIs that are available.

It is easier to call them directly. You can do it by matching C compiler's data types, layouts, and function call/return sequences. For functions, it can be directly called from D. You do not need wrapper function, argument swizzling or to put the functions in separate DLLs.  For example: A simple C function like this;

extern (C) int strcmp (char* s1, char* s2); can be called like this;

import std.string;

int myDfunction (char [] s){

return strcmp (std.string.toStringz (s), “foo”);

}

Here D understands how C functions are managed and the call/return sequence. There are no const or volatile type modifiers in D. So for declaring a C function that uses those type modifiers, you just need to drop those keywords from the declaration. C code explicitly manages memory with calls to malloc() and free().

On the other side D allocates memory using the D garbage collector. So no explicit free's are necessary for this. For global's, C globa'ls can be accessed directly from D. C global's have the C naming convention and so it must be in an extern (C) block.

Related Questions