Call C function - Access violation
Gary Willoughby via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jan 3 12:21:20 PST 2016
On Sunday, 3 January 2016 at 19:24:46 UTC, TheDGuy wrote:
> On Sunday, 3 January 2016 at 13:25:04 UTC, Gary Willoughby
> wrote:
>> On Sunday, 3 January 2016 at 13:23:25 UTC, Gary Willoughby
>> wrote:
>>> I think I've noticed one problem with the code above. You are
>>> using `text.ptr`. You shouldn't do that because you are
>>> passing a pointer not an array. Just use `text`.
>>
>> Forget this line, my mistake. Use `toStringz` and pass a
>> pointer instead of an array.
>
> Hi and thanks for your answer. My code looks now like this:
>
> void main(string[] args){
> const(char)* val = "Hello World".std.string.toStringz;
> char* result = write(val);
> const(char)[] s = cstr2dstr(result);
> writeln(s);
> readln(); //keep the window open
> }
>
> But now i get the error: "function expected before(), not
> package std of type void" (refering to line 2).
>
> And if i define the variable 'value' as 'const(char)*' i also
> have to rewrite my C-function to accept const(char)*...
Use an import.
import std.string;
import std.conv;
void main(string[] args) {
auto value = toStringz("Hello World");
auto result = write(value);
auto s = to!(string)(result);
writeln(s);
}
Also all string literals in D are zero terminated so you could
write the call like this:
auto result = write("Hello World");
More information about the Digitalmars-d-learn
mailing list