2010-02-26 10 views
0

我有一个项目,其中我使用System.Runtime.InteropServices以下面的方式定义一个结构,以便它打包到字节边界并准备发送到串行端口,并从那里到嵌入式系统。 (商业敏感的名字已被删除)如何使用代理类操作打包结构中的数据?

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); 
    } 
} 

什么,我试图做的是做的是使用构造函数使用

Field1 = new UTCTime(ref this.rawdata.Field1) 

包裹分配给这些字段的代理类引用将结构中的原始数据转换为允许在计算对应于时间的32位整数之前进行更高级操作的类。我的代理类是

public class UTCTime : Field 
{ 
    private Uint32 dataReference; 

    public UTCTime(ref rawData) 
    { 
    // code to do reference assignment here? 
    } 
} 

有什么办法有dataReference为字段1参考这样的,我的代理类是能够操纵的包装结构中的数据?

在此先感谢, 托马斯。

回答

1

这是不可能的。

一般的经验法则是,你不能存储对管理对象的引用。

通过引用传递允许您使用使用尽可能多的参考。但你必须切换到不安全的块与IntPtr的完成你想要做的。