www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Empty string is null?

reply hasen <hasan.aljudy gmail.com> writes:
How to pass it to C functions that expect a non-null string? 
Specifically to GTK+ (using gtkD)

I also asked this on stackoverflow 
http://stackoverflow.com/questions/931360/

    ------------

Using D1 with phobos

I have a text entry field, instance of gtk.Entry.Entry,

calling setText("") raises a run time error

   Gtk-CRITICAL **: gtk_entry_set_text: assertion `text != NULL' failed

Why? It seems to be a problem with D, I tried this:

   string empty = "";
   assert (empty != null);
   my_entry.setText(empty)

The program terminated as the assertion failed.

How can I work around this?
May 30 2009
next sibling parent Mike Wey <mike-wey example.com> writes:
hasen wrote:
 How to pass it to C functions that expect a non-null string? 
 Specifically to GTK+ (using gtkD)
 
 I also asked this on stackoverflow 
 http://stackoverflow.com/questions/931360/
 
    ------------
 
 Using D1 with phobos
 
 I have a text entry field, instance of gtk.Entry.Entry,
 
 calling setText("") raises a run time error
 
   Gtk-CRITICAL **: gtk_entry_set_text: assertion `text != NULL' failed
 
 Why? It seems to be a problem with D, I tried this:
 
   string empty = "";
   assert (empty != null);
   my_entry.setText(empty)
 
 The program terminated as the assertion failed.
 
 How can I work around this?
 
As a workaround you could use setText("\0"); This shouldn't be needed in GtkD svn r685. -- Mike Wey
May 31 2009
prev sibling parent Mike Parker <aldacron gmail.com> writes:
hasen wrote:
 How to pass it to C functions that expect a non-null string? 
 Specifically to GTK+ (using gtkD)
 
 I also asked this on stackoverflow 
 http://stackoverflow.com/questions/931360/
 
    ------------
 
 Using D1 with phobos
 
 I have a text entry field, instance of gtk.Entry.Entry,
 
 calling setText("") raises a run time error
 
   Gtk-CRITICAL **: gtk_entry_set_text: assertion `text != NULL' failed
 
 Why? It seems to be a problem with D, I tried this:
 
   string empty = "";
   assert (empty != null);
   my_entry.setText(empty)
 
 The program terminated as the assertion failed.
 
 How can I work around this?
 
This is one of those D quirks that trip people up quite frequently. When testing a string for null using the regular ==/!= operators, an empty string will always result the same as a null string. To truly test for null, use the is/!is operators instead. This will not take the contents of the string into account. The following will do what you expect: string empty = ""; assert(empty !is null); my_entry.setText(empty); And since strings, like all arrays, are structs with the length and ptr fields, you can also do either of the following: assert(empty.ptr != null); assert(empty.ptr !is null);
May 31 2009