C# DllImport – Using the C ++ DLL / Windows API

The strong point of C # is that it is easy to import Dll and Windows API developed in C ++ as well as .Net Framework.

The part that provides this functionality is DllImport.

DllImport is available under the following conditions.

It must also be using System.Runtime.InteropServices in Microsoft Visual Studio

[DllImport (string dllName) ]  
public sealed class DllImportAttribute : Attribute

A description of DllImport can be found here.


Let’s look at an example.

using System.Runtime.InteropServices;

class Example
    // Use DllImport to import the Win32 MessageBox function.
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
    static void Main()
        // Call the MessageBox function using platform invoke.
       int result = MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);

As you can see from the above, you can use Dllimport to specify the Dll you want to use, and to provide functions that exist inside the Dll through extern. Parameters required for the function can also be defined together at this time.
The following example is similar to the one used to call the INI configuration file provided by Kernel32.dll.

using System.Runtime.InteropServices;

class Itka
	private static extern long WritePrivateProfileString(  
		String section,
		String key,
		String val,
		String filePath);

	private void WriteINI
		WritePrivateProfileString("ITKA", "NAME", "allmnet", "C:\\");


Facebook Comments

Leave A Reply

Detection ADBlockPlease, Disable or add to white list on our site.