Char * character and string

Jonathan M Davis jmdavisProg at gmx.com
Thu Mar 1 21:06:02 PST 2012


On Friday, March 02, 2012 05:51:14 Chris Pons wrote:
> Hello,
> I am trying to work with SDL and one of their functions takes a
> char * file as a function a parameter. However, i'm running into
> trouble how to actually set this variable in my constructor.
> 
> I am getting a problem where if I use a pointer to a char and set
> it as "test.bmp" I get an error stating "cannot implicitly
> convert expression (file) of type string to char*. After that I
> decided to try to set file to 'test.bmp' instead, and in that
> case I get: "Unterminated character constant" . Although I am
> familiar with what this error is referring to, I do not know how
> to add a terminator in D.
> 
> This is the function that I intend to use the filename in:
> **Note the function LoadBMP is the one that REQUIRES a pointer to
> a char
> --------------------------------------
> 	SDL_Surface * Load(char * file)
> 	{
> 		SDL_Surface * Temp = null;
> 
> 		if((Temp = SDL_LoadBMP(file)) == null)
> 			return null;
> 
> 		Surface = SDLDisplayFormat(Temp);
> 
> 		SDL_FreeSurface(Temp);
> 
> 		return Surface;
> 	}
> ----------------------------------------
> 
> This is the constructor that is giving me the error:
> ----------------------------------------------------------
> 	char * file;
> 
> 	this()
> 	{
> 		this.filename = "test.bmp";
> 	}
> -------------------------------------------------------------

Use std.string.toStringz (or std.utf.toUTFz if immutable(char)* doesn't cut 
it).

Regardless, be careful of passing char* to C code. Even if the C code keeps 
the pointer, it won't stop the GC from collecting it. The D code needs to have 
reference to it of some kind (though a pointer in your struct as you appeart 
to be doing should be plenty as long as an instance of the struct remains in 
the D code - as opposed to passing it to the C code and then not having it in 
the D code anymore, which would be no better than just passing the char* to 
the C code without keeping a reference to it).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list