I have written a small util in an app that syncs the time from a time server, which uses the Windows API functions GetSystemTime and SetSystemTime. It was all working fine, but now every time I call Get/SetSystemTime I get an error:
FatalExecutionEngineError was detected Message: The runtime has encountered a fatal error. The address of the error was at 0x792bee10, on thread 0x48c. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
Now as the only unsafe code is a call to the Win32 functions (is that even unsafe??) it seems it cant be in my code – that and i havent changed anythig since it was actually working…
Any ideas what might be going on here?
The Win32 calls are made using:
public class SystemTime
{
public ushort Year;
public ushort Month;
public ushort DayOfWeek;
public ushort Day;
public ushort Hour;
public ushort Minute;
public ushort Second;
public ushort Millisecond;
public static implicit operator SystemTime(DateTime dt)
{
SystemTime rval = new SystemTime();
rval.Year = (ushort)dt.Year;
rval.Month = (ushort)dt.Month;
rval.Day = (ushort)dt.Day;
rval.DayOfWeek = (ushort)dt.DayOfWeek;
rval.Hour = (ushort)dt.Hour;
rval.Minute = (ushort)dt.Minute;
rval.Second = (ushort)dt.Second;
rval.Millisecond = (ushort)dt.Millisecond;
return rval;
}
public static implicit operator DateTime(SystemTime st)
{
return new DateTime(st.Year, st.Month, st.Day, st.Hour, st.Minute, st.Second, st.Millisecond);
}
};
[DllImport("kernel32.dll", EntryPoint = "GetSystemTime")]
public extern static void Win32GetSystemTime(ref SystemTime sysTime);
[DllImport("kernel32.dll", EntryPoint = "SetSystemTime")]
public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
EDIT: Now the very same code (unmodified) is giving me an AccessViolation ???
Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
Since you are defining SYSTEMTIME as a class, when you pass it by reference you are actually passing a pointer to a pointer but on the unmanaged side it is expecting a pointer to a SYSTEMTIME structure.
Either change your definition of SYSTEMTIME to a struct and pass it by reference as you are doing now. Or leave it as a class and change your declares to:
Personally, I would change it to a struct.