是否可以为MarshalAs属性类定义自定义UnmanagedType?具体来说,我想将一个长的into时间转换为DateTime类型。就像这样:
[MarshalAs(UnmanagedType.LongTimeUnix)]
public DateTime Time;
我必须将自定义的LongTimeUnix枚举类型放在哪里,以及将时间转换代码放在哪里:
public static DateTime ConvertUnix2DateTime(long timeStamp)
{
DateTime DT = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DT = DT.AddSeconds(timeStamp);
return DT;
}
当将数据传输到
(SomeStruct)Marshal.PtrToStructure(
IntPtr,
typeof(SomeStruct));
我希望长时间的unix自动与上面的代码sinppet进行转换。我是否必须继承MarshalAs类并将转换写入这个类?谢谢你,尤尔根
更新这里是自定义封送处理程序:
class MarshalTest : ICustomMarshaler
{
public void CleanUpManagedData(object ManagedObj)
{
throw new NotImplementedException();
}
public void CleanUpNativeData(IntPtr pNativeData)
{
throw new NotImplementedException();
}
public int GetNativeDataSize()
{
return 8;
}
public IntPtr MarshalManagedToNative(object ManagedObj)
{
throw new NotImplementedException();
}
public object MarshalNativeToManaged(IntPtr pNativeData)
{
long UnixTime = 0;
try
{
UnixTime = Marshal.ReadInt64(pNativeData);
}
catch (Exception e)
{
QFXLogger.Error(e, "MarshalNativeToManaged");
}
DateTime DT = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DT = DT.AddSeconds(UnixTime);
return DT;
}
}
以下是类的定义:
unsafe public struct MT5ServerAttributes
{
/// <summary>
/// Last known server time.
/// </summary>
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalTest))]
public DateTime CurrentTime;
//[MarshalAs(UnmanagedType.U8)]
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalTest))]
public DateTime TradeTime;
}
最后,从非托管内存封送数据的代码:
try
{
MT5ServerAttributes MT5SrvAttributes = (MT5ServerAttributes)Marshal.PtrToStructure(mMT5Proxy.MT5InformationProxy.ServerData,
typeof(MT5ServerAttributes));
}
catch (Exception e)
{
QFXLogger.Error(e, "ConsumeCommand inner");
}
当运行此操作时,将引发以下超异常(这不是PtrToStructure的直接异常!)不能封送类型为‘QFX_DLL.MT5ServerAttributes’的字段'CurrentTime‘:无效的托管/非托管类型组合( DateTime类必须与Struct配对)。有什么想法吗?
发布于 2011-09-30 12:09:59
不能将自己的内容添加到枚举中,但可以使用UnmanagedType.CustomMarshaler
。若要指定要使用自定义类型封送它,请执行以下操作。
MSDN有一个完整的章节专门讨论这个问题。
你最终会做一些这样的事情:
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MyCustomMarshaler))]
public DateTime Time;
然后将MyCustomMarshaler实现为ICustomMarshaler
。
https://stackoverflow.com/questions/7610069
复制相似问题