-
[C#] DLLImport로 외부 DLL 함수 호출하기프로그래밍/C# + Unity 2023. 12. 11. 11:39728x90
DLLImport
DllImport는 P/Invoke(플랫폼호출) 방법 중 하나로 C#에서 .NET 외의 코드나 라이브러리, 특히 C나 C++로 작성된 코드를 호출할 때 사용한다. 이를 사용하여 C# 코드에서 외부 DLL 함수를 호출한다.
소스 코드
아래는 DllImport를 사용하는 기본적인 예제로 kernel32.dll에 있는 MessageBox 함수를 호출한다.
using System; using System.Runtime.InteropServices; class Program { // kernel32.dll에 있는 MessageBox 함수 선언 [DllImport("kernel32.dll", SetLastError = true)] public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type); static void Main() { // MessageBox 함수 호출 MessageBox(IntPtr.Zero, "Hello, DllImport!", "Greetings", 0); } }
위의 코드에서 DllImport 함수를 통해 kernel32.dll 내부의 MessageBox 함수를 C#에서 마치 일반적인 C# 함수처럼 호출한다. 이 처럼 DllImport는 외부 DLL이나 네이티브 코드를 사용하는 경우에 유용하지만, 네이티브 코드와의 상호 작용 시에 메모리 관리와 타입 일치에 주의해야 한다.
참고
https://learn.microsoft.com/ko-kr/dotnet/standard/native-interop/pinvoke
728x90댓글