exern (C) linkage problem
bearophile
bearophileHUGS at lycos.com
Mon Jul 19 10:03:52 PDT 2010
Lars T. Kyllingstad:
> 2. For D strings in general the \0 must be added, but this is very easy
> to forget. Therefore, when passing strings to C functions I always use
> the std.string.toStringz() function. It takes a D string, adds a \0 if
> necessary, and returns a pointer to the first character.
>
> string s = getAStringFromSomewhere();
> dbdefine(toStringz(s));
The C code has to use those string pointers with lot of care.
The D type system can help you remember to use the toStringz, this is just an idea:
import std.string: toStringz;
typedef char* Cstring;
extern(C) Cstring strcmp(Cstring s1, Cstring s2);
Cstring toCString(T)(T[] s) {
return cast(Cstring)toStringz(s);
}
void main() {
auto s1 = "abba";
auto s2 = "red";
// auto r = strcmp(toCString(s1), s2); // compile error
auto r = strcmp(toCString(s1), toCString(s2)); // OK
}
Unfortunately Andrei has killed the useful typedef. So you have to use a struct with alias this, that often doesn't work.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list