C callback receives bad pointer argument
bearophile
bearophileHUGS at lycos.com
Thu Jun 30 15:43:31 PDT 2011
Marco Cosentino:
> Translated correctly the C callback style into D delegates types with alias.
D has function pointers too.
> Managed some segment faluts happened when not using toStringz() with
> some "strings"
For this kind of bugs I suggest to use the D type system in a smarter way. With extern you allowed to give what type you want to the C char* arguments, so you are free to use another type. An example:
import std.stdio: writeln;
import std.string: toStringz;
typedef const char* ccharPtr;
// example of C function, with smarter string type
extern(C) size_t strlen(ccharPtr str);
ccharPtr toStringz2(string s) {
return cast(ccharPtr)toStringz(s);
}
void main() {
string s1 = "this is ";
string s2 = s1 ~ "just a string";
writeln(s2.length);
auto cs = toStringz2(s2);
writeln(strlen(cs));
}
Now that typedef is deprecated what solution do you suggest instead?
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list