본문 바로가기
.Net

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

by 올엠 2020. 10. 29.
반응형

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

 

System.Runtime.InteropServices 네임스페이스

COM interop 및 플랫폼 호출 서비스를 지원하는 다양한 멤버를 제공합니다. Provides a wide variety of members that support COM interop and platform invoke services. 이러한 서비스를 잘 모르는 경우 비관리 코드와의 상

docs.microsoft.com

[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

 

extern modifier - C# Reference

extern modifier - C# Reference

docs.microsoft.com

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

 

WritePrivateProfileStringA function (winbase.h) - Win32 apps

Copies a string into the specified section of an initialization file.

docs.microsoft.com

 

반응형