Fixed Byte Array to String

O

O.B.

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?


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace TestApp.DIS
{
/// <summary>
/// Specifies the marking for an entity.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
unsafe public struct EntityMarking
{
/// <summary>
/// An 8-bit enumeration (see Section 4 of EBV-DOC).
/// </summary>
[FieldOffset(0)]
public byte characterSet; // 1 byte

/// <summary>
/// A byte array of 11 characters that represents the marking.
/// </summary>
[FieldOffset(1)]
public fixed byte marking[11]; // 11 bytes

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 = Convert.ToChar(marking);
}
return (new String(chars));
}
}
}
 
R

rossum

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 = Convert.ToChar(marking);
}
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 = Convert.ToChar(EMptr->marking);
}

} // end fixed statement

return (new String(chars));
}

HTH

rossum
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top