Create C header files from
Dennis
dkorpel at gmail.com
Tue Feb 17 16:43:05 UTC 2026
On Tuesday, 17 February 2026 at 15:27:20 UTC, MaxNaderer wrote:
> I have looked into __traits and I guess i need to go this way.
You can use traits, I've done something like that for Pascal
instead of C. It roughly looks like:
```D
string headerFromDModules(modules...)()
{
string result = "#pragma once\n";
foreach (mod; modules)
{
foreach (mem; __traits(allMembers, mod))
{
static if (is(typeof(__traits(getMember, mod, mem)) ==
function))
{
alias F = __traits(getMember, mod, mem);
static if (functionLinkage!F == "C")
{
result ~= functionToHeader!(mem, F);
}
}
}
}
result ~= "\n";
return result;
}
```
`string functionToHeader(string mem, alias F)()` then has to
introspect Parameters!F, ParameterIdentifierTuple!F,
ParameterStorageClassTuple!F, and ReturnType!F and generate a C
string accordingly. It can be used like so:
```D
import pkg.a;
import pkg.b;
import std;
void main()
{
File("header.h", "w").write(headerFromDModules!(pkg.a, pkg.b);
}
```
> The perfect way would be to get a XML or json from the
> functions so that the bindings can be easily automated
dmd has the `-X` flag to generate JSON which I'd wager has
sufficient information to generate C headers, but you can also
open an enhancement request in the issue tracker
(https://github.com/dlang/dmd/issues) to make dmd directly
generate C headers because it sounds like a worthwhile feature.
More information about the Digitalmars-d-learn
mailing list