


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); } }Later, after searching for information, an article mentioned that C# is managed memory. Now we need to pass the structure array, which is
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; };But after such improvements, the running results are still not ideal, and the values are either wrong or not changed. What is the reason for this? After constantly searching for information, I finally found an article, which mentioned the transfer of structures. Some can be done as above, but some cannot, especially when the parameter is a structure pointer or a structure array pointer in C++. , pointers should also be used to correspond to C# calls, and the following code will be improved later.
[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); } }It should be noted that at this time is not byte aligned in BCB, it will sometimes be larger than the normal structure. The body size is 2 bytes more. Because BCB defaults to 2-byte sorting, and VC defaults to 1-byte sorting. To solve this problem, either add byte alignment to the BCB structure, or open two more bytes (if there are more) in C#. The byte alignment code is as follows.
#pragma pack(push,1) struct Info { int OrderNO; char UniqueCode[32]; float CpuPercent; }; #pragma pack(pop)Use Marsh.AllocHGlobal to open up memory space for structure pointers. The purpose is to convert unmanaged memory. So if Marsh.AllocHGlobal is not used, is there any other way?
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; } #endregionWhen you really can’t think of how to transmit data, you can consider transmitting it as a byte array (even an integer is acceptable, as long as it is 4 bytes (under 32 bits)), as long as the length corresponds to After getting the data, it needs to be converted into the required data according to the type rules, which can generally achieve the purpose.
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!

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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