i have a project wherein i am using System.Runtime.InteropServices to define a struct in the following manner such that it is packed to byte boundaries and ready to send to a serial port and from there to an embedded system. (business sensitive names have been removed)
public class ControlCommandClass
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct ControlCommandData
{
public Uint32 Field1;
public Uint16 Field2;
public Sbyte Field3;
public Uint32 Field4;
}; // this struct is 11 bytes in memory!
private ControlCommandData rawdata;
public UTCTime Field1;
public ControlCommandClass()
{
this.Field1 = new UTCTime(ref this.rawdata.Field1);
}
}
What i am trying to do is to do is to use the constructor to assign references to those fields to a proxy class using
Field1 = new UTCTime(ref t开发者_如何学JAVAhis.rawdata.Field1)
to wrap the raw data in the structure to a class which allows more advanced operations before calculating the 32 bit integer which corresponds to the time. my proxy class is
public class UTCTime : Field
{
private Uint32 dataReference;
public UTCTime(ref rawData)
{
// code to do reference assignment here?
}
}
Is there any way to have dataReference as a reference to Field1 such that my proxy class is able to manipulate the data in the packed structure?
Thanks in advance, Thomas.
That is not possible as is.
General rule of thumb is that you cannot store a reference to a managed object.
Passing by reference allows you to use a reference as much as you want. But you'd have to switched to an unsafe block with IntPtr's to accomplish what you're trying to do.
精彩评论