How to use C code in D

Laeeth Isharc via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 23 12:04:58 PDT 2017


On Thursday, 23 March 2017 at 18:10:20 UTC, Dillen Meijboom wrote:
> 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;
> }
> ```

https://dlang.org/phobos/std_process.html#.environment means it's 
already done for you.

C global variables are __gshared.

Reading other people's source code - starting with standard 
library and maybe look at some of the bindings and wrappers on 
code.dlang.org.

IRC chat to get a quick answer most of the time.


More information about the Digitalmars-d-learn mailing list