call an external dll method in csharp

To call a method from an external DLL in C#, you need to use Platform Invocation Services (P/Invoke) and the appropriate marshaling to convert the data types between C# and the DLL. Here are the basic steps:

  1. Define the DLL method signature in C# using DllImport attribute. This attribute instructs the runtime to load the dynamic library at runtime and bind with the exported function.
main.cs
[DllImport("mydll.dll")]
public static extern int MyDLLMethod(int arg1, string arg2);
86 chars
3 lines
  1. Use appropriate marshaling to convert the data types between C# and the DLL. You may need to marshal data types such as string, bool, char[], struct, and pointer.
main.cs
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
143 chars
3 lines
  1. Call the DLL method in your C# code.
main.cs
int result = MyDLLMethod(42, "hello");
MessageBox(IntPtr.Zero, $"Result = {result}", "DLL Call Result", 0);
108 chars
3 lines

gistlibby LogSnag