toStringz, and memory management, also fromStringz

Joel Christensen joelcnz at gmail.com
Fri Sep 9 18:00:02 PDT 2011


Hi,

In the std.string document at toStringz it has this note:

Important Note: When passing a char* to a C function, and the C function 
keeps it around for any reason, make sure that you keep a reference to 
it in your D code. Otherwise, it may go away during a garbage collection 
cycle and cause a nasty bug when the C code tries to use it.

What does it mean, and what is an example of how to do it?

It's not done like this is it?

char* a = cast(char*)toStringz( "test" );
char* b = cast(char*)toStringz( "word" );
hold ~= a;
hold ~= b;

char* cstr2 = al_get_config_value( cfg, a, b );

My programs using a C library do crash when exiting some times.

Also, how do I go the other way round, some thing like toDString. I've 
made my own version. I can't seem to find fromStringz.

Thanks for any help.

- Joelcnz


More information about the Digitalmars-d-learn mailing list