Help passing D strings to C libs

Trass3r un at known.com
Mon Mar 14 10:54:57 PDT 2011


> I'm having trouble passing D strings (char[]) to SDL, in particular
> SDL_LoadBMP(), I keep receiving a segfault.
>
> Heres the code:
>
> void setImg(string path) {
>     // concat null terminating char to string and cast to c type string  
> when
>     // passing to SDL_LoadBMP()
>     path ~= "\0";
>     image = SDL_LoadBMP( cast(char*)path );
> }
>
> and the value of path is "./resources/cannon.bmp"
>
> I'm using SDL 1.2.14 and DMD 1.067 on Ubuntu 10.10

Well strings are put into read-only space on Linux and I guess this is  
also the case for D1.
Since you are doing a ~= it probably tries to alter that value and crashes.

You should use something like SDL_LoadBMP(cast(char*)(path ~ "\0")) if you  
really wanted to convert it manually.
But the proper way to convert a string to a C char* is to use toStringz.


More information about the Digitalmars-d-learn mailing list