是否可以为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;
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));