.NET Platform Invoke (P/Invoke) Sample
February 12, 2008 – 10:03 amRecently someone asked me to help them call an unmanaged C++ DLL from a C# application, whereupon I promptly pointed them to the MSDN documentation on P/Invoke. Unfortunately (as I later learned) the documentation is very descriptive if you’re trying to use a Windows DLL, but it doesn’t help you understand how to create the unmanaged C++ DLL in the first place. Here’s how you do it:
- In Visual C++ (I use 2008) create a new Win32 Project, and then choose “DLL” in the “Application Settings” page of the Create Project wizard that follows.
- If the project name I had chosen was “TestDll,” I would have a file named TestDll.cpp in my project. This is where we’ll put our functions to be called by C#. Open this file for editing.
- Add a function that performs the action you want. I will create a function (for demonstration purposes only) called AddNumbers that, obviously, adds two numbers and returns the result (the __declspec(dllexport) tells the C++ compiler to extern this function):
extern “C” __declspec(dllexport)int AddNumbers(int a, int b) { return a + b; } - Compile this project.
- Create a C# application and extern the C++ DLL function as follows. This tells the C# compiler that this function will be available at runtime:
[DllImport(”TestDll.dll”)] static extern int AddNumbers(int a, int b);
- Then you can just call AddNumbers from C# just as if it was another function in your C# project.