Access string as const char* |
![]() |
|
|
|
|
|
The GetString method is rarely used; in most cases, when your program needs to access the contents of a Str object as a C-style string, it can just typecast the object to const STRCHAR*.
The returned value is a null-terminated, read-only string. The operation is very fast because no copying occurs -- the internal string representation is directly returned. However, it is important not to modify the returned buffer, or Str Library might crash.
Example: use printf() with a Str object
Str s ("Sample text");
printf("The string content is: [%s]\n", (const STRCHAR*) s);
Note that, when calling variable-argument functions (printf, sprintf, etc...) Microsoft Visual C will allow you to pass the string object instance directly as a parameter, without the typecast. Str will still work this way due to a special precaution taken in its implementation. However, we recommend that you always typecast for clarity and safety. gcc will not allow you to pass the object without typecasting.
Example 2: mix C-style strings and Str objects
Str s ("12");
char buf[80];
// Note how there is no need to typecast, the compiler
// will automatically perform the conversion for the 2nd
// parameter of strcat()
strcat (strcpy (buf, "Value is"), s);
See also: Basic operations, ANSI / Unicode conversion