On Thu, 04 Jan 2007 10:31:31 -0600, "O.B." <(E-Mail Removed)>
wrote:
>In the example below, I'm trying to convert a fixed byte array to a
>string. I get an error about needing to use "fixed" but I have no clue
>where to apply it. Help?
>
>
> public override string ToString()
> {
> char[] chars = new char[11];
> for (int i = 0; i < 11; i++)
> {
> // ERROR: You cannot use fixed size buffers contained in unfixed
> // expressions. Try using the fixed statement.
> chars[i] = Convert.ToChar(marking[i]);
> }
> return (new String(chars));
> }
> }
The text to this error says: "This error occurs if you use the fixed
sized buffer in an expression involving a class that is not itself
fixed. The runtime is free to move the unfixed class around to
optimize memory access, which could lead to errors when using the
fixed sized buffer. To avoid this error, use the fixed keyword on the
statement."
You have to temporarily fix your structure for the duration of the
fixed statement by fixing a pointer to it, and using that pointer to
access your fixed size byte array.
Try this:
public override string ToString()
{
char[] chars = new char[11];
// This is the fixed statement
fixed (EntityMarking* EMptr = &this)
{
for (int i = 0; i < 11; i++)
{
// Access marking[] via the fixed pointer.
chars[i] = Convert.ToChar(EMptr->marking[i]);
}
} // end fixed statement
return (new String(chars));
}
HTH
rossum
|