How to use C code in D

Dillen Meijboom via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 23 11:10:20 PDT 2017


Hi there,

I'm learning D for a while because it's really easy to use C-code 
in D.
The problem is that I don't really get how to deal with the data 
structures defined in C in D.

At one time for instance I've tried to get all environment 
variables on a POSIX system. I succeeded but I think it can be 
done way easier.

So my question basically is:
1. How can I learn to use C code in D? Is there any good tutorial 
or other packages that deal with this a lot?
2. Is the way I'm currently doing it okay or is it wrong and do I 
need to do something else?

As a reference, I'm currently using the following D code to get 
all environment variables:

```
import std.array;
import std.conv: to;
import std.string: fromStringz;

extern (C) extern const char** environ;

string[string] getenv() {
	string[string] env;
	char* line;

	for (auto data = cast(char**)environ; (line = *data) != null; 
++data) {
		auto keyval = to!string(fromStringz(line)).split('=');

		env[keyval[0]] = keyval[1];
	}

	return env;
}
```


More information about the Digitalmars-d-learn mailing list