using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Linq; using System.Text; namespace EdgeTech.SonarComms.Demo { class Utils { const string _versionInfo = "$Header: Utils.cs Revision:1.3 Tue Apr 17 13:45:46 2012 mps $"; private string versionInfo; public static Object BufToStruct(byte[] MyBuf, Type MyType) { GCHandle MyGC = GCHandle.Alloc(MyBuf, GCHandleType.Pinned); Object MyStruct = Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), MyType); //* Copy the 'unmanaged' buffer to struct MyGC.Free(); return (MyStruct); } public static bool StructToBuf(Object MyStruct, byte[] MyBuf) { return (StructToBuf(MyStruct, -1, MyBuf)); } public static bool StructToBuf(Object MyStruct, int MySize, byte[] MyBuf) { int Siz = (MySize == -1) ? Marshal.SizeOf(MyStruct) : MySize; if (MyBuf.Length < Siz) // Marshal.SizeOf(MyStruct)) return (false); //* Use the 'System.Runtime.InteropServices.Marshal services to copy TpCmd to MyBuf IntPtr UnBuf = Marshal.AllocCoTaskMem(Siz); //Marshal.SizeOf(MyStruct)); //* Create an 'unmanaged' buffer Marshal.StructureToPtr(MyStruct, UnBuf, true); //* Copy TpCmd to the 'unmanaged' buffer Marshal.Copy(UnBuf, MyBuf, 0, Siz); //Marshal.SizeOf(MyStruct)); //* Copy the 'unmanaged' buffer to MyBuf Marshal.FreeCoTaskMem(UnBuf); //* Free the 'unmanaged' buffer return (true); } // printThrottle is used to manage the flow of Console.WriteLine statements to the console window // printThrottle=5: All Console.WriteLine statements are written to display // printThrottle=0: No Console.WriteLine statements are written to display private static int printThrottle = 4; public static void setPrintThrottle(int k) { printThrottle = k; } public static int getPrintThrottle() { return printThrottle; } public static bool doThisPrint(int k) { if (k <= printThrottle) { return true; } else { return false; } } public static void flagFatalError(string errString) { Console.WriteLine("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"); Console.WriteLine("* Fatal error encountered: *"); Console.WriteLine("* {0}", errString); Console.WriteLine("* Sonar CLI will now shut down... *"); Console.WriteLine("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"); } // The following method applies to Utils.cs only public string getVersionInfo() { versionInfo = _versionInfo.Remove(0, 9); string endStr = " mps $"; char[] end = endStr.ToCharArray(); versionInfo = versionInfo.TrimEnd(end); return versionInfo; } } }