A Programmer's Dilema: juggling with C, BetterC, D, Macros and Cross Compiling, etc.

Mike Parker aldacron at gmail.com
Mon May 1 10:39:44 UTC 2023


On Monday, 1 May 2023 at 09:17:14 UTC, Eric P626 wrote:
>> This is a false dilemma: D has full C compatibility.
>
> From what I understand, D can use C, but C cannot use D? It's 
> like C++: C++ can call C but C cannot call C++.

> 50% or more of my code will be put in re-usabled libraries. If 
> I want people to use those libs, I would need to compile them 
> in C or better C. Because betterC seems to create C libraries. 
> If D can make C libraries, then indeed, I could do everything 
> in D.
>

D is ABI-compatible with C. BetterC has nothing to do with it. 
And if you're using BetterC just because you're linking with a C 
library, you're crippling your D code. That's not really a good 
use case for it.

Any D function marked as `extern(C)` can be called from C. As 
long as you have a C header file defining the functions and the 
appropriate C declarations any custom types you have, the C code 
will have no idea it's calling into a D library.

In your D library:
```D
// This function can be called from C
extern(C) void functionForTheCAPI(const(char)* str) {
     import std.conv : to;
     doSomething(to!string(str));
}

// This is a D function that cannot be called from C
void doSomething(string s) { ... }
```

In the corresponding C header:
```C
extern void functionForTheCAPI(const char* str);
```

Just `#include` the C header in your C code, link with the D 
library, and you're good to go. Make sure to include a function 
somewhere in your D library's C API to initialize DRuntime:

```D
import core.runtime;

extern(C) int initialize() { return Runtime.initialize(); }
```

Add the declaration to a C header and you're good to go.




More information about the Digitalmars-d-learn mailing list