기타 VB.NET에서 System.Reflection을 이용한 동적 DLL 사용하기: 예제와 설명
페이지 정보

본문
위 코드는 "example.dll"이라는 DLL을 동적으로 호출하여 두 숫자를 더하는 간단한 예제입니다.
이를 실행하면 DLL의 함수를 성공적으로 호출하여 결과를 출력할 것입니다.
이 예제를 통해 VB.NET에서 동적 DLL을 사용하는 기본적인 방법을 이해할 수 있습니다.
동적 DLL을 사용하면 프로그램의 유연성을 높일 수 있으며, 여러 라이브러리를 효율적으로 관리할 수 있습니다.
이런식으로 우리는 Windows API라고 많이 알고 사용하는 방식 중 하나입니다.
System.Reflection을 이용한 동적 DLL 사용
VB.NET에서 System.Reflection 네임스페이스를 활용하여 동적 DLL을 사용하는 방법은 유연하고 강력한 방법입니다.
이를 통해 실행 중에 DLL을 로드하고 메서드를 호출할 수 있습니다.
아래 예제를 통해 VB.NET에서 System.Reflection을 이용한 동적 DLL 사용하는 방법을 자세히 알아보겠습니다.
Imports System Namespace ExampleNamespace     Public Class ExampleClass         Public Function Add(ByVal a As Integer, ByVal b As Integer) As Integer             Return a + b         End Function     End Class End Namespace  | 
위 코드를 ExampleClass.vb 파일로 저장하세요. 그리고 다음 명령어를 사용하여 컴파일하여 example.dll을 생성할 수 있습니다.
이제 example.dll이 준비되었습니다. 이제 VB.NET 코드에서 이 DLL을 사용하는 방법을 보여줄게요.
Imports System.Reflection Module MainModule     Sub Main()         ' DLL 파일 경로 설정         Dim dllPath As String = "C:\path\to\your\example.dll"         ' DLL 파일 로드         Dim assembly As Assembly = Assembly.LoadFrom(dllPath)         ' DLL 내의 클래스 및 메서드 정보 가져오기         Dim className As String = "ExampleNamespace.ExampleClass"         Dim methodName As String = "Add"         Dim type As Type = assembly.GetType(className)         Dim methodInfo As MethodInfo = type.GetMethod(methodName)         ' 메서드 호출         Dim instance As Object = Activator.CreateInstance(type)         Dim result As Integer = CType(methodInfo.Invoke(instance, New Object() {5, 3}), Integer)         ' 결과 출력         Console.WriteLine("결과: " & result)     End Sub End Module  | 
위 코드를 실행하면, example.dll을 동적으로 호출하여 두 숫자를 더하는 결과를 출력할 수 있습니다.
Public Class ExampleClass     Public Shared Function Add(ByVal a As Integer, ByVal b As Integer) As Integer         MsgBox(a.ToString() & " + " & b.ToString() & " = " & (a + b).ToString())         Return a + b     End Function End Class  | 
DLL을 사용하는 VB.NET 코드:
 Imports System.Reflection Module MainModule     Sub Main()         ' DLL 파일 경로 설정         Dim dllPath As String = "DLL의_경로\example.dll"         ' DLL 파일 로드         Dim assembly As Assembly = Assembly.LoadFile(dllPath)         ' DLL 내의 클래스 및 메서드 정보 가져오기         Dim className As String = "루트네임스페이스.ExampleClass"         Dim methodName As String = "Add"         Dim type As Type = assembly.GetType(className)         Dim methodInfo As MethodInfo = type.GetMethod(methodName)         ' 메서드 호출         Dim returnValue As Integer = DirectCast(methodInfo.Invoke(Nothing, New Object() {5, 3}), Integer)         ' 결과 출력         Console.WriteLine("결과: " & returnValue.ToString())     End Sub End Module  | 
위 코드를 실행하면, example.dll을 동적으로 호출하여 두 숫자를 더하는 결과를 출력할 수 있습니다. 
- 이전글[VB.NET] 컨트롤 삭제 여부 확인하는 방법 24.05.08
 - 다음글VB.NET 마스터하기: 효율적인 Extension 메서드 사용법 24.04.17
 
댓글목록
등록된 댓글이 없습니다.



