


Detailed explanation of the solution to C# calling C++DLL to pass structure array
This article mainly introduces relevant information on the ultimate solution for C# to call C++DLL to pass a structure array. Friends in need can refer to
C# to call C++DLL to pass a structure. The ultimate solution for body arrays
When developing a project, it is necessary to call the C++ encapsulated DLL. Common types generally correspond to C#. Just use DllImport to introduce the function# from the DLL. ## will do. But when a structure, structure array, or structure pointer is passed, you will find that there is no corresponding type in C#. What to do at this time? The first reaction is that C# also defines the structure and then passes it on as a parameter. However, when we define a structure and want to pass parameters into it, an exception will be thrown, or the structure will be passed in, but the return value is not what we want. After Debugging tracking, we found that, Those values have not changed at all, the code is as follows.
[DllImport("workStation.dll")] private static extern bool fetchInfos(Info[] infos); public struct Info { public int OrderNO; public byte[] UniqueCode; public float CpuPercent; }; private void buttonTest_Click(object sender, EventArgs e) { try { Info[] infos=new Info[128]; if (fetchInfos(infos)) { MessageBox.Show("Fail"); } else { string message = ""; foreach (Info info in infos) { message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}", info.OrderNO, Encoding.UTF8.GetString(info.UniqueCode), info.CpuPercent ); } MessageBox.Show(message); } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } }
StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] public struct Info { public int OrderNO; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] UniqueCode; public float CpuPercent; };
[DllImport("workStation.dll")] private static extern bool fetchInfos(IntPtr infosIntPtr); [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] public struct Info { public int OrderNO; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] UniqueCode; public float CpuPercent; }; private void buttonTest_Click(object sender, EventArgs e) { try { int workStationCount = 128; int size = Marshal.SizeOf(typeof(Info)); IntPtr infosIntptr = Marshal.AllocHGlobal(size * workStationCount); Info[] infos = new Info[workStationCount]; if (fetchInfos(infosIntptr)) { MessageBox.Show("Fail"); return; } for (int inkIndex = 0; inkIndex < workStationCount; inkIndex++) { IntPtr ptr = (IntPtr)((UInt32)infosIntptr + inkIndex * size); infos[inkIndex] = (Info)Marshal.PtrToStructure(ptr, typeof(Info)); } Marshal.FreeHGlobal(infosIntptr); string message = ""; foreach (Info info in infos) { message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}", info.OrderNO, Encoding.UTF8.GetString(info.UniqueCode), info.CpuPercent ); } MessageBox.Show(message); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } }
#pragma pack(push,1) struct Info { int OrderNO; char UniqueCode[32]; float CpuPercent; }; #pragma pack(pop)
one-dimensional array of equal size, is that okay? The answer is yes, the implementation is given below.
[DllImport("workStation.dll")] private static extern bool fetchInfos(IntPtr infosIntPtr); [DllImport("workStation.dll")] private static extern bool fetchInfos(byte[] infos); [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] public struct Info { public int OrderNO; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] UniqueCode; public float CpuPercent; }; private void buttonTest_Click(object sender, EventArgs e) { try { int count = 128; int size = Marshal.SizeOf(typeof(Info)); byte[] inkInfosBytes = new byte[count * size]; if (fetchInfos(inkInfosBytes)) { MessageBox.Show("Fail"); return; } Info[] infos = new Info[count]; for (int inkIndex = 0; inkIndex < count; inkIndex++) { byte[] inkInfoBytes = new byte[size]; Array.Copy(inkInfosBytes, inkIndex * size, inkInfoBytes, 0, size); infos[inkIndex] = (Info)bytesToStruct(inkInfoBytes, typeof(Info)); } string message = ""; foreach (Info info in infos) { message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}", info.OrderNO, Encoding.UTF8.GetString(info.UniqueCode), info.CpuPercent ); } MessageBox.Show(message); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } #region bytesToStruct /// <summary> /// Byte array to struct or classs. /// </summary> /// <param name=”bytes”>Byte array</param> /// <param name=”type”>Struct type or class type. /// Egg:class Human{...}; /// Human human=new Human(); /// Type type=human.GetType();</param> /// <returns>Destination struct or class.</returns> public static object bytesToStruct(byte[] bytes, Type type) { int size = Marshal.SizeOf(type);//Get size of the struct or class. if (bytes.Length < size) { return null; } IntPtr structPtr = Marshal.AllocHGlobal(size);//Allocate memory space of the struct or class. Marshal.Copy(bytes, 0, structPtr, size);//Copy byte array to the memory space. object obj = Marshal.PtrToStructure(structPtr, type);//Convert memory space to destination struct or class. Marshal.FreeHGlobal(structPtr);//Release memory space. return obj; } #endregion
The above is the detailed content of Detailed explanation of the solution to C# calling C++DLL to pass structure array. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to the Access Modifiers in C#. We have discussed the Introduction Types of Access Modifiers in C# along with examples and outputs.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Guide to Web Services in C#. Here we discuss an introduction to Web Services in C# with technology use, limitation, and examples.
