Working with external libraries expands the capabilities of Visual Basic, allowing the use of not only standard classes but also third-party components — both .NET libraries (DLLs) and classic COM objects.
Originally, VB was primarily focused on interacting with COM components (ActiveX, OCX), allowing such libraries to be connected through "Project – References". With the emergence of VB.NET, the ability to reference .NET assemblies was added, making it more convenient to use external methods via P/Invoke (Declare).
The main difficulty is the need to properly choose the integration method to avoid runtime errors, compatibility issues, and resource leaks when interacting with external code.
In .NET, to use .NET libraries or registered COM components, Add Reference is used, which adds a reference to the assembly; to call procedures from native DLLs, Declare is applied.
Example using a .NET library (Add Reference):
' After adding the .NET reference Imports System.IO Dim reader As New StreamReader("file.txt") Dim line As String = reader.ReadLine() reader.Close()
Example calling a function from WinAPI (Declare):
' Calling a function from user32.dll (WinAPI) Declare Function MessageBeep Lib "user32" (ByVal wType As Integer) As Boolean Sub TestBeep() MessageBeep(0) End Sub
Key features:
Can the Imports statement be used to load functions from external DLLs?
No, the Imports statement only simplifies accessing namespaces within linked assemblies but cannot be used for dynamically linking functions from native DLLs.
Is it necessary to register .NET assemblies for use through Add Reference in VB.NET?
No, .NET libraries are connected by simply adding a reference, while registration through regsvr32 is only required for COM libraries.
Can .NET methods be connected through Declare, not just native Win32 functions?
No, Declare is only applied to functions from regular (non-.NET) DLLs that export stdcall/FARPROC functions. .NET functions are called through Add Reference/Imports.
A developer decided to use a third-party .NET library via Declare without studying the documentation and encountered a compilation error.
Pros:
Cons:
Correctly adding a .NET reference through Add Reference, then using Imports and creating instances of the required classes.
Pros:
Cons: