Interop

35.1 P/Invoke

Marshalling: StructLayout, MarshalAs, SafeHandle, callbacks via delegates (keep a reference alive!), Marshal.AllocHGlobal/FreeHGlobal.

The CsWin32 source generator is C#-only. Hand-write VB signatures or wrap them in a C# project.

Imports System.Runtime.InteropServices
Friend NotInheritable Class NativeMethods
    Private Sub New()
    End Sub

    <DllImport("user32.dll", CharSet:=CharSet.Unicode, SetLastError:=True)>
    Friend Shared Function MessageBoxW(hWnd As IntPtr, text As String, caption As String, type As UInteger) As Integer
    End Function

    <DllImport("kernel32.dll", SetLastError:=True)>
    Friend Shared Function GetDiskFreeSpaceEx(directory As String, ByRef freeBytes As ULong, ByRef totalBytes As ULong, ByRef totalFree As ULong) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    Friend Declare Unicode Function GetComputerNameW Lib "kernel32" (buffer As Text.StringBuilder, ByRef size As Integer) As Boolean   ' VB Declare syntax
End Class

Dim free, total, totalFree As ULong
If NativeMethods.GetDiskFreeSpaceEx("C:\", free, total, totalFree) Then
    Console.WriteLine($"{free / 1024 ^ 3:N1} GB free")
Else
    Throw New ComponentModel.Win32Exception(Marshal.GetLastWin32Error())
End If

35.2 COM and Office

Early binding: add a COM reference → interop assembly (EmbedInteropTypes). Late binding: CreateObject with Option Strict Off (Module 24).

Release COM objects (Marshal.ReleaseComObject / FinalReleaseComObject) and avoid "two dots" chains that leak RCWs in Office automation.

Expose VB classes to COM (for VBA/VB6/classic ASP consumers):.NET 5+: <EnableComHosting>true</EnableComHosting> + regsvr32 X.comhost.dll..NET Framework: regasm /codebase /tlb.

Prefer file-format libraries (ClosedXML, Open XML SDK, DocX/Xceed, PdfPig/QuestPDF) over Office automation for server and batch scenarios.

<ComVisible(True), Guid("5E1C2B3A-1111-2222-3333-444455556666"), ClassInterface(ClassInterfaceType.None)>
Public Class TaxCalculator
    Implements ITaxCalculator
    Public Function Calculate(amount As Double) As Double Implements ITaxCalculator.Calculate
        Return amount * 0.18
    End Function
End Class