On Tuesday, 19 February 2013 at 16:23:45 UTC, Chris wrote:
I have written a DLL that I load into a Python program.
Everything works fine (DLL is loaded via ctypes, functions can
be called and are executed). Only the string handling is giving
me a bit of a headache. The string in D is always complete
garbage. I have written Python modules in D (with C wrappers)
before and got them to work. But the DLL in D seems to be a
completely different beast. Does anyone have experience with it?
Python uses ctypes, e.g.
myDLL = CDLL("myDLL") / WinDLL("myDLL")
myDLL.printThis(c_char_p("Hello world")) /
myDLL.printThis(create_string_buffer("Hello world"))
The D side looks like like this:
export void printThis(ref char[] str) {
printf("%s\n", str); // prints "Hello World"
writeln(str); // prints garbage
}
OR
export void printThis(char* str) {
printf("%s\n", str); // prints garbage
writeln(str); // prints garbage
}
What am I doing wrong / missing here? I guess it has something
to do with the pointers.
Thanks!
prin
D doesn't use null termination for it's strings, strings are
immutable(char)[]. You can form a D slice from a pointer by going
slice = ptr[0..length]
where length is the length of the array the pointer represents.
You can't just take a c style string and expect writeln to work
with it.
Also, I think you should have extern(C) in the function
definition.