public static void Main() { // initialize all members DSBrowseInfo dsbi = new DSBrowseInfo(); dsbi.structSize = Marshal.SizeOf(dsbi); dsbi.dlgCaption = "The container picker"; dsbi.treeViewTitle = "Pick a container for this example."; dsbi.path = new string( new char[MAX_PATH]); dsbi.pathSize = dsbi.path.Length; dsbi.flags = LibWrap.DSBI_ENTIREDIRECTORY; dsbi.objectClass = new string( new char[MAX_PATH]); dsbi.objectClassSize = dsbi.objectClass.Length; Console.WriteLine("Call DSBrowseForContainer..."); int status = LibWrap.DsBrowseForContainerW(ref dsbi); Console.WriteLine("The status is " + status); if (status == 1) { Console.WriteLine("The path is " + dsbi.path); } else { Console.WriteLine("Call failed!"); } }
public static void Main() { OpenFileName ofn = new OpenFileName(); ofn.structSize = Marshal.SizeOf(ofn); ofn.filter = "Log files\0*.log\0Batch files\0*.bat\0"; ofn.file = new String(new char[256]); ofn.maxFile = ofn.file.Length; ofn.fileTitle = new String(new char[64]); ofn.maxFileTitle = ofn.fileTitle.Length; ofn.initialDir = "C:\\"; ofn.title = "Open file called using platform invoke..."; ofn.defExt = "txt"; if (LibWrap.GetOpenFileName(ofn)) { Console.WriteLine("Selected file with full path: {0}", ofn.file); Console.WriteLine("Selected file name: {0}", ofn.fileTitle); Console.WriteLine("Offset from file name: {0}", ofn.fileOffset); Console.WriteLine("Offset from file extension: {0}", ofn.fileExtension); } }
public static void Main() { FindData fd = new FindData(); IntPtr handle = LibWrap.FindFirstFile("C:\\*.*", fd); Console.WriteLine("The first file: {0}", fd.fileName); }
public static void Main() { DsBrowseInfo dsbi = new DsBrowseInfo { Size = Marshal.SizeOf(typeof(DsBrowseInfo)), PathSize = DsBrowseInfo.MAX_PATH, Caption = "Container Selection Example", Title = "Select a container from the list.", ReturnFormat = LibWrap.ADS_FORMAT_WINDOWS, Flags = LibWrap.DSBI_ENTIREDIRECTORY, Root = "LDAP:", Path = new string(new char[DsBrowseInfo.MAX_PATH]) }; // Initialize remaining members... int status = LibWrap.DsBrowseForContainerW(ref dsbi); if ((LibWrap.BrowseStatus)status == LibWrap.BrowseStatus.BrowseOk) { Console.WriteLine(dsbi.Path); } else { Console.WriteLine("No path returned."); } }
public static void Main() { Console.WriteLine("\nPassing OSVersionInfo as class"); OSVersionInfo osvi = new OSVersionInfo(); osvi.OSVersionInfoSize = Marshal.SizeOf(osvi); LibWrap.GetVersionEx(osvi); Console.WriteLine("Class size: {0}", osvi.OSVersionInfoSize); Console.WriteLine("Major version: {0}", osvi.majorVersion); Console.WriteLine("Minor version: {0}", osvi.minorVersion); Console.WriteLine("Build number: {0}", osvi.buildNumber); Console.WriteLine("Platform ID: {0}", osvi.platformId); Console.WriteLine("Version: {0}", osvi.versionString); Console.WriteLine("\nPassing OSVersionInfo as struct"); OSVersionInfo2 osvi2 = new OSVersionInfo2(); osvi2.OSVersionInfoSize = Marshal.SizeOf(osvi2); LibWrap.GetVersionEx2(ref osvi2); Console.WriteLine("Struct size: {0}", osvi2.OSVersionInfoSize); Console.WriteLine("Major version: {0}", osvi2.majorVersion); Console.WriteLine("Minor version: {0}", osvi2.minorVersion); Console.WriteLine("Build number: {0}", osvi2.buildNumber); Console.WriteLine("Platform ID: {0}", osvi2.platformId); Console.WriteLine("Version: {0}", osvi2.versionString); }
public static void Main() { FPtr cb = new FPtr(App.DoSomething); LibWrap.TestCallBack(cb, 99); FPtr2 cb2 = new FPtr2(App.DoSomething2); LibWrap.TestCallBack2(cb2, "abc"); }
public static void Main() { Console.WriteLine("C# SysTime Sample using Platform Invoke"); SystemTime st = new SystemTime(); LibWrap.GetSystemTime(st); Console.Write("The Date is: "); Console.Write("{0} {1} {2}", st.month, st.day, st.year); }
public static string OpenFilePanel(string filter, string defExt) { ++m_filePanelsRefCount; UnityEngine.Debug.Log("Incrementing FileExplorer ref count, new value: " + m_filePanelsRefCount); string filename = string.Empty; #if UNITY_EDITOR filename = UnityEditor.EditorUtility.OpenFilePanel("Open file", "", defExt); if (filename == string.Empty) { --m_filePanelsRefCount; UnityEngine.Debug.Log("Decrementing FileExplorer ref count, new value: " + m_filePanelsRefCount); throw new FileExplorerExitException("Could not open file"); } #else UnityEngine.Debug.Log("Native file explorer: Preparing to create OpenFileName dialog"); OpenFileName openChartFileDialog = new OpenFileName(); UnityEngine.Debug.Log("Native file explorer: Preparing to set struct size"); openChartFileDialog.structSize = Marshal.SizeOf(openChartFileDialog); UnityEngine.Debug.Log("Native file explorer: Preparing to set filter"); openChartFileDialog.filter = filter; UnityEngine.Debug.Log("Native file explorer: Preparing to set file array"); openChartFileDialog.file = new String(new char[256]); UnityEngine.Debug.Log("Native file explorer: Preparing to set max file length"); openChartFileDialog.maxFile = openChartFileDialog.file.Length; UnityEngine.Debug.Log("Native file explorer: Preparing to set file title size"); openChartFileDialog.fileTitle = new String(new char[64]); UnityEngine.Debug.Log("Native file explorer: Preparing to set max file title length"); openChartFileDialog.maxFileTitle = openChartFileDialog.fileTitle.Length; UnityEngine.Debug.Log("Native file explorer: Preparing to set initial directory"); openChartFileDialog.initialDir = ""; UnityEngine.Debug.Log("Native file explorer: Preparing to set title"); openChartFileDialog.title = "Open file"; UnityEngine.Debug.Log("Native file explorer: Preparing to set defExt"); openChartFileDialog.defExt = defExt; if (LibWrap.GetOpenFileName(openChartFileDialog)) { filename = openChartFileDialog.file; } else { --m_filePanelsRefCount; UnityEngine.Debug.Log("Decrementing FileExplorer ref count, new value: " + m_filePanelsRefCount); throw new FileExplorerExitException("Could not open file"); } #endif --m_filePanelsRefCount; UnityEngine.Debug.Log("Decrementing FileExplorer ref count, new value: " + m_filePanelsRefCount); return(new string(filename.ToCharArray())); }
public static void Main() { SystemTime st = new SystemTime(); LibWrap.GetSystemTime(st); Console.Write("The Date and Time is: "); Console.Write("{0:00}/{1:00}/{2} at ", st.month, st.day, st.year); Console.WriteLine("{0:00}:{1:00}:{2:00}", st.hour, st.minute, st.second); }
public static void Main() { IntPtr instancePtr = LibWrap.CreateTestClass(); int res = LibWrap.TestThisCalling(instancePtr, 9); Console.WriteLine("\nResult: {0} \n", res); LibWrap.DeleteTestClass(instancePtr); }
public static void Main() { // Call GetSystemDirectory. StringBuilder sysDirBuffer = new StringBuilder(256); LibWrap.GetSystemDirectory(sysDirBuffer, sysDirBuffer.Capacity); // ... // Call GetCommandLine. IntPtr cmdLineStr = LibWrap.GetCommandLine(); string commandLine = Marshal.PtrToStringAuto(cmdLineStr); }
public static void Main() { TextWriter tw = System.Console.Out; GCHandle gch = GCHandle.Alloc(tw); CallBack cewp = new CallBack(CaptureEnumWindowsProc); // Platform invoke prevents the delegate from being garbage // collected before the call ends. LibWrap.EnumWindows(cewp, (IntPtr)gch); gch.Free(); }
public static void Run() { TextWriter tw = System.Console.Out; GCHandle gch = GCHandle.Alloc(tw); CallBack cewp = new CallBack(CaptureEnumWindowsProc); // platform invoke will prevent delegate to be garbage collected // before call ends LibWrap.EnumWindows(cewp, GCHandle.ToIntPtr(gch)); gch.Free(); }
public static void Main() { LibWrap.MsgBox(0, "Correct text", "MsgBox Sample", 0); LibWrap.MsgBox2(0, "Incorrect text", "MsgBox Sample", 0); try { LibWrap.MsgBox3(0, "No such function", "MsgBox Sample", 0); } catch (EntryPointNotFoundException) { Console.WriteLine("EntryPointNotFoundException thrown as expected!"); } }
public static void Run() { FileStream fs = new FileStream("HandleRef.txt", FileMode.Open); HandleRef hr = new HandleRef(fs, fs.SafeFileHandle.DangerousGetHandle()); StringBuilder buffer = new StringBuilder(5); int read = 0; // platform invoke will hold reference to HandleRef until call ends LibWrap.ReadFile(hr, buffer, 5, out read, 0); Console.WriteLine("Read with struct parameter: {0}", buffer); LibWrap.ReadFile2(hr, buffer, 5, out read, null); Console.WriteLine("Read with class parameter: {0}", buffer); }
public static void Main() { Console.WriteLine("Calling SetData using AsAny... \n"); LibWrap.SetData(LibWrap.DataType.DT_I2, (short)12); LibWrap.SetData(LibWrap.DataType.DT_I4, (long)12); LibWrap.SetData(LibWrap.DataType.DT_R4, (float)12); LibWrap.SetData(LibWrap.DataType.DT_R8, (double)12); LibWrap.SetData(LibWrap.DataType.DT_STR, "abcd"); Console.WriteLine("\nCalling SetData using overloading... \n"); double d = 12; LibWrap.SetData2(LibWrap.DataType.DT_R8, ref d); LibWrap.SetData2(LibWrap.DataType.DT_STR, "abcd"); }
public static void Main() { // If delagate will be used just inside one call, this syntax // is ok since platform invoke will protect delegate from GC // until call ends. If unmanaged side could store delegate and // try to use it later than caller should protect delegate until // unmanaged side is finished. FPtr cb = new FPtr(App.DoSomething); LibWrap.TestCallBack(cb, 99); FPtr2 cb2 = new FPtr2(App.DoSomething2); LibWrap.TestCallBack2(cb2, "abc"); }
public static unsafe void UsingUnsafePointer() { int size; MyUnsafeStruct *pResult; LibWrap.TestOutArrayOfStructs(out size, &pResult); MyUnsafeStruct *pCurrent = pResult; for (int i = 0; i < size; i++, pCurrent++) { Console.WriteLine("Element {0}: {1} {2}", i, Marshal.PtrToStringAnsi(pCurrent->buffer), pCurrent->size); Marshal.FreeCoTaskMem(pCurrent->buffer); } Marshal.FreeCoTaskMem((IntPtr)pResult); }
public static void Main() { FileStream fs = new FileStream("HandleRef.txt", FileMode.Open); // Wraps the FileStream handle in HandleRef to prevent it // from being garbage collected before the call ends. HandleRef hr = new HandleRef(fs, fs.SafeFileHandle.DangerousGetHandle()); StringBuilder buffer = new StringBuilder(5); int read = 0; // Platform invoke holds a reference to HandleRef until the call // ends. LibWrap.ReadFile(hr, buffer, 5, out read, IntPtr.Zero); Console.WriteLine("Read {0} bytes with struct parameter: {1}", read, buffer); LibWrap.ReadFile2(hr, buffer, 5, out read, null); Console.WriteLine("Read {0} bytes with class parameter: {1}", read, buffer); }
public static void Main() { // call GetSystemDirectory StringBuilder sysDirBuffer = new StringBuilder(256); LibWrap.GetSystemDirectory(sysDirBuffer, sysDirBuffer.Capacity); Console.WriteLine("SysDir: {0}", sysDirBuffer); // call GetUserName StringBuilder userNameBuffer = new StringBuilder(128); int size = userNameBuffer.Capacity; LibWrap.GetUserName(userNameBuffer, ref size); Console.WriteLine("UserName: {0}", userNameBuffer); IntPtr cmdLineStr = LibWrap.GetCommandLine(); String commandLine = Marshal.PtrToStringAuto(cmdLineStr); Console.WriteLine("CommandLine: {0}", commandLine); }
public static void Main() { int errCode = Marshal.GetLastWin32Error(); Console.WriteLine("\nThe last error before MessageBox is called: {0}", errCode); Console.WriteLine("Calling MessageBox with wrong parameters..."); int res = LibWrap.MessageBox(IntPtr.Zero, "Correct text", "PInvoke MsgBox Sample", 999); Console.WriteLine("Call result: {0}", res); errCode = Marshal.GetLastWin32Error(); Console.WriteLine("The last error after MessageBox is called: {0}", errCode); StringBuilder buffer = new StringBuilder(256); LibWrap.FormatMessage(LibWrap.FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, errCode, 0, buffer, buffer.Capacity, IntPtr.Zero); Console.WriteLine("Error message: {0}", buffer); }
public static void Main() { MyUnion mu = new MyUnion(); mu.i = 99; LibWrap.TestUnion(mu, 1); mu.d = 99.99; LibWrap.TestUnion(mu, 2); MyUnion2_1 mu2_1 = new MyUnion2_1(); mu2_1.i = 99; LibWrap.TestUnion2(mu2_1, 1); MyUnion2_2 mu2_2 = new MyUnion2_2(); mu2_2.str = "*** string ***"; LibWrap.TestUnion2(mu2_2, 2); }
public static void UsingMarshaling() { int size; IntPtr outArray; LibWrap.TestOutArrayOfStructs(out size, out outArray); MyStruct[] manArray = new MyStruct[size]; IntPtr current = outArray; for (int i = 0; i < size; i++) { manArray[i] = new MyStruct(); Marshal.PtrToStructure(current, manArray[i]); //Marshal.FreeCoTaskMem( (IntPtr)Marshal.ReadInt32( current )); Marshal.DestroyStructure(current, typeof(MyStruct)); current = (IntPtr)((long)current + Marshal.SizeOf(manArray[i])); Console.WriteLine("Element {0}: {1} {2}", i, manArray[i].buffer, manArray[i].size); } Marshal.FreeCoTaskMem(outArray); }
public static void Main() { Console.WriteLine("\nPassing OSVersionInfo as a class"); OSVersionInfo osvi = new OSVersionInfo(); osvi.OSVersionInfoSize = Marshal.SizeOf(osvi); LibWrap.GetVersionEx(osvi); Console.WriteLine("Class size: {0}", osvi.OSVersionInfoSize); Console.WriteLine("OS Version: {0}.{1}", osvi.MajorVersion, osvi.MinorVersion); Console.WriteLine("\nPassing OSVersionInfo as a struct"); OSVersionInfo2 osvi2 = new OSVersionInfo2(); osvi2.OSVersionInfoSize = Marshal.SizeOf(osvi2); LibWrap.GetVersionEx2(ref osvi2); Console.WriteLine("Struct size: {0}", osvi2.OSVersionInfoSize); Console.WriteLine("OS Version: {0}.{1}", osvi2.MajorVersion, osvi2.MinorVersion); }
public static string ShowWindowsDialog() { OpenFileName ofn = new OpenFileName(); ofn.structSize = Marshal.SizeOf(ofn); ofn.filter = "0"; ofn.file = new String(new char[256]); ofn.maxFile = ofn.file.Length; ofn.fileTitle = new String(new char[64]); ofn.maxFileTitle = ofn.fileTitle.Length; ofn.initialDir = "C:\\"; ofn.title = "Open file"; ofn.defExt = ""; LibWrap.GetOpenFileName(ofn); Console.WriteLine("File Selection: " + ofn.file); return(ofn.file); }
public static void Main() { // String as result. string str = LibWrap.TestStringAsResult(); Console.WriteLine("\nString returned: {0}", str); // Initializes buffer and appends something to the end so the whole // buffer is passed to the unmanaged side. StringBuilder buffer = new StringBuilder("content", 100); buffer.Append((char)0); buffer.Append('*', buffer.Capacity - 8); MyStrStruct mss; mss.buffer = buffer.ToString(); mss.size = mss.buffer.Length; LibWrap.TestStringInStruct(ref mss); Console.WriteLine("\nBuffer after Unicode function call: {0}", mss.buffer); StringBuilder buffer2 = new StringBuilder("content", 100); buffer2.Append((char)0); buffer2.Append('*', buffer2.Capacity - 8); MyStrStruct2 mss2; mss2.buffer = buffer2.ToString(); mss2.size = mss2.buffer.Length; LibWrap.TestStringInStructAnsi(ref mss2); Console.WriteLine("\nBuffer after Ansi function call: {0}", mss2.buffer); }
unsafe public static void serverThread() { UdpClient udpClient = new UdpClient(SERVER_PORT); string dataTemplate = "sync "; while (true) { IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); string returnData = Encoding.ASCII.GetString(receiveBytes); if (returnData.IndexOf(dataTemplate) != -1) { SystemTime systime = new SystemTime(); LibWrap.GetSystemTime(systime); int startIndex = dataTemplate.Length; int allData = returnData.Length; string dataString = returnData.Substring(startIndex, allData - startIndex); DateTime data = Convert.ToDateTime(dataString); systime.Hour = (ushort)data.Hour; systime.Minute = (ushort)data.Minute; systime.Second = (ushort)data.Second; LibWrap.Win32SetSystemTime(systime); Console.WriteLine("Время синхронизировано!"); break; } } // Console.ReadLine(); }
string GetAudioFile() { string audioFilepath = string.Empty; #if UNITY_EDITOR audioFilepath = UnityEditor.EditorUtility.OpenFilePanel("Select Audio", "", "mp3,ogg,wav"); #else OpenFileName openAudioDialog = new OpenFileName(); openAudioDialog = new OpenFileName(); openAudioDialog.structSize = Marshal.SizeOf(openAudioDialog); openAudioDialog.file = new String(new char[256]); openAudioDialog.maxFile = openAudioDialog.file.Length; openAudioDialog.fileTitle = new String(new char[64]); openAudioDialog.maxFileTitle = openAudioDialog.fileTitle.Length; openAudioDialog.initialDir = ""; openAudioDialog.title = "Open file"; openAudioDialog.defExt = "txt"; openAudioDialog.filter = "Audio files (*.ogg,*.mp3,*.wav)\0*.mp3;*.ogg;*.wav"; if (LibWrap.GetOpenFileName(openAudioDialog)) { audioFilepath = openAudioDialog.file; } else { throw new System.Exception("Could not open file"); } #endif return(audioFilepath); }
public static void Main() { // Structure with a pointer to another structure. MyPerson personName; personName.first = "Mark"; personName.last = "Lee"; MyPerson2 personAll; personAll.age = 30; IntPtr buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(personName)); Marshal.StructureToPtr(personName, buffer, false); personAll.person = buffer; Console.WriteLine("\nPerson before call:"); Console.WriteLine("first = {0}, last = {1}, age = {2}", personName.first, personName.last, personAll.age); int res = LibWrap.TestStructInStruct(ref personAll); MyPerson personRes = (MyPerson)Marshal.PtrToStructure(personAll.person, typeof(MyPerson)); Marshal.FreeCoTaskMem(buffer); Console.WriteLine("Person after call:"); Console.WriteLine("first = {0}, last = {1}, age = {2}", personRes.first, personRes.last, personAll.age); // Structure with an embedded structure. MyPerson3 person3 = new MyPerson3(); person3.person.first = "John"; person3.person.last = "Evans"; person3.age = 27; LibWrap.TestStructInStruct3(person3); // Structure with an embedded array. MyArrayStruct myStruct = new MyArrayStruct(); myStruct.flag = false; myStruct.vals = new int[3]; myStruct.vals[0] = 1; myStruct.vals[1] = 4; myStruct.vals[2] = 9; Console.WriteLine("\nStructure with array before call:"); Console.WriteLine(myStruct.flag); Console.WriteLine("{0} {1} {2}", myStruct.vals[0], myStruct.vals[1], myStruct.vals[2]); LibWrap.TestArrayInStruct(ref myStruct); Console.WriteLine("\nStructure with array after call:"); Console.WriteLine(myStruct.flag); Console.WriteLine("{0} {1} {2}", myStruct.vals[0], myStruct.vals[1], myStruct.vals[2]); }
public static void Main() { // array ByVal int[] array1 = new int[10]; Console.WriteLine("Integer array passed ByVal before call:"); for (int i = 0; i < array1.Length; i++) { array1[i] = i; Console.Write(" " + array1[i]); } int sum1 = LibWrap.TestArrayOfInts(array1, array1.Length); Console.WriteLine("\nSum of elements:" + sum1); Console.WriteLine("\nInteger array passed ByVal after call:"); foreach (int i in array1) { Console.Write(" " + i); } // array ByRef int[] array2 = new int[10]; int size = array2.Length; Console.WriteLine("\n\nInteger array passed ByRef before call:"); for (int i = 0; i < array2.Length; i++) { array2[i] = i; Console.Write(" " + array2[i]); } IntPtr buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(size) * array2.Length); Marshal.Copy(array2, 0, buffer, array2.Length); int sum2 = LibWrap.TestRefArrayOfInts(ref buffer, ref size); Console.WriteLine("\nSum of elements:" + sum2); if (size > 0) { int[] arrayRes = new int[size]; Marshal.Copy(buffer, arrayRes, 0, size); Marshal.FreeCoTaskMem(buffer); Console.WriteLine("\nInteger array passed ByRef after call:"); foreach (int i in arrayRes) { Console.Write(" " + i); } } else { Console.WriteLine("\nArray after call is empty"); } // matrix ByVal const int DIM = 5; int[,] matrix = new int[DIM, DIM]; Console.WriteLine("\n\nMatrix before call:"); for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { matrix[i, j] = j; Console.Write(" " + matrix[i, j]); } Console.WriteLine(""); } int sum3 = LibWrap.TestMatrixOfInts(matrix, DIM); Console.WriteLine("\nSum of elements:" + sum3); Console.WriteLine("\nMatrix after call:"); for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { Console.Write(" " + matrix[i, j]); } Console.WriteLine(""); } // string array ByVal String[] strArray = { "one", "two", "three", "four", "five" }; Console.WriteLine("\n\nString array before call:"); foreach (String s in strArray) { Console.Write(" " + s); } int lenSum = LibWrap.TestArrayOfStrings(strArray, strArray.Length); Console.WriteLine("\nSum of string lengths:" + lenSum); Console.WriteLine("\nString array after call:"); foreach (String s in strArray) { Console.Write(" " + s); } // struct array ByVal MyPoint[] points = { new MyPoint(1, 1), new MyPoint(2, 2), new MyPoint(3, 3) }; Console.WriteLine("\n\nPoints array before call:"); foreach (MyPoint p in points) { Console.WriteLine("x = {0}, y = {1}", p.x, p.y); } int allSum = LibWrap.TestArrayOfStructs(points, points.Length); Console.WriteLine("\nSum of points:" + allSum); Console.WriteLine("\nPoints array after call:"); foreach (MyPoint p in points) { Console.WriteLine("x = {0}, y = {1}", p.x, p.y); } // struct with strings array ByVal MyPerson[] persons = { new MyPerson("Kim", "Akers"), new MyPerson("Adam", "Barr"), new MyPerson("Jo", "Brown") }; Console.WriteLine("\n\nPersons array before call:"); foreach (MyPerson pe in persons) { Console.WriteLine("first = {0}, last = {1}", pe.first, pe.last); } int namesSum = LibWrap.TestArrayOfStructs2(persons, persons.Length); Console.WriteLine("\nSum of name lengths:" + namesSum); Console.WriteLine("\n\nPersons array after call:"); foreach (MyPerson pe in persons) { Console.WriteLine("first = {0}, last = {1}", pe.first, pe.last); } }