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
https://docs.microsoft.com/ko-kr/dotnet/api/system.runtime.interopservices?view=netframework-4.7.2

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

A description of DllImport can be found here.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/extern

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
{
	[DllImport("kernel32.dll")]
	private static extern long WritePrivateProfileString(  
		String section,
		String key,
		String val,
		String filePath);

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

https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-writeprivateprofilestringa

Facebook Comments

Leave A Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.