
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1080
|
Chapter 19: Unsafe Code
Solution
Use the ToCharArray method of the string type to create a char* character array:
public static void ConvertStringToCharPtr(string str)
{
unsafe
{
fixed (char* pStr = str.ToCharArray( ))
{
// Display some of the characters.
Console.WriteLine(pStr->ToString( )); // Could also have been
// written as pStr[0].ToString( ).
Console.WriteLine(pStr[1].ToString( ));
Console.WriteLine(pStr[2].ToString( ));
Console.WriteLine(pStr[3].ToString( ));
}
}
}
Discussion
To get a character array from a string object, you can use the overloaded
ToCharArray method on the string object. This method is overloaded to accept no
arguments and convert the entire string to a character array or to take two integer
arguments and convert only a substring of the entire string to a character array.
These two integer parameters hold a
startIndex value and a length value. The sub-
string starting at the
startIndex position in the string and ending at the (startIndex
+ length) position in the string is converted to a character array.
See Also
See Recipes 19.3–19.7; see the “Unsafe Code Tutorial” and the “Fixed Statement”
topics in the MSDN documentation.
19.9 Declaring a Fixed-Size Structure
with an Embedded Array
Problem
You require a structure to contain a fixed-size array in which the ...