Import function from unmanaged C++ DLL

suggest change

Here is an example of how to import a function that is defined in an unmanaged C++ DLL. In the C++ source code for “myDLL.dll”, the function add is defined:

extern "C" __declspec(dllexport) int __stdcall add(int a, int b)
{
    return a + b;
}

Then it can be included into a C# program as follows:

class Program
{
    // This line will import the C++ method.
    // The name specified in the DllImport attribute must be the DLL name.
    // The names of parameters are unimportant, but the types must be correct.
    [DllImport("myDLL.dll")]
    private static extern int add(int left, int right);

    static void Main(string[] args)
    {
        //The extern method can be called just as any other C# method.
        Console.WriteLine(add(1, 2));
    }
}

See Calling conventions and C++ name mangling for explanations about why extern "C" and __stdcall are necessary.

Finding the dynamic library

When the extern method is first invoked the C# program will search for and load the appropriate DLL. For more information about where is searched to find the DLL, and how you can influence the search locations see this stackoverflow question.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Interoperability:
* Import function from unmanaged C++ DLL

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script
149 Interoperability