using System.Runtime.InteropServices; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int AddDelegate(int a, int b); public static class UnmanagedLibrary { [DllImport("myunmanagedlibrary.dll")] public static extern int PerformAddition(AddDelegate add, int a, int b); } public class ManagedCode { public static void Main() { var addDelegate = new AddDelegate((a, b) => a + b); int result = UnmanagedLibrary.PerformAddition(addDelegate, 10, 20); Console.WriteLine(result); // 30 } }
using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct Point { public int X; public int Y; } public static class UnmanagedLibrary { [DllImport("myunmanagedlibrary.dll")] public static extern void TranslatePoint(ref Point point, int deltaX, int deltaY); } public class ManagedCode { public static void Main() { var point = new Point { X = 10, Y = 20 }; UnmanagedLibrary.TranslatePoint(ref point, 5, 5); Console.WriteLine(point.X + ", " + point.Y); // 15, 25 } }In this example, we define a struct named `Point` that represents a point in 2D space. It has two fields, `X` and `Y`, that represent the coordinates of the point. We also define a static class named `UnmanagedLibrary` that contains an external method named `TranslatePoint`. This method takes a reference to a `Point` struct and two integers, `deltaX` and `deltaY`, that represent how much to move the point in the X and Y directions. Finally, we define a `ManagedCode` class that creates an instance of `Point`, calls `TranslatePoint`, and prints the updated coordinates to the console. Package library: System.Runtime.InteropServices.