Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Interop and Migration

Interop: P/Invoke, COM and Mixed Solutions

Learn VB.NET interop - calling C# libraries from VB, P/Invoke with DllImport, marshaling strings and structs, COM and Office automation, late binding, plus runnable C# stand-ins.

Real systems are rarely written in one language. A VB.NET application may use a library written in C#, call a function in a Windows DLL, or automate Excel through COM. Interoperability ("interop") is the set of mechanisms for that. This lesson goes from the easiest (another .NET language) to the hardest (native code and COM).

Honest limits. The VB.NET compiler, Windows system DLLs and COM servers (Excel, Word) do not exist on this site's Linux runner, so VB code and Windows calls here are read-only and no results of such calls are claimed. The runnable blocks are C# stand-ins that use the cross-platform parts of the same machinery (DllImport against the C library, marshaling, reflection-based late binding).

.NET to .NET: reference another project

Any .NET language can reference the compiled assembly of another. In a Visual Studio solution you right-click Dependencies and add a project reference; with the CLI:

TEXT
dotnet new classlib -lang "C#" -o Geometry
dotnet add VbApp/VbApp.vbproj reference Geometry/Geometry.csproj

Then in VB:

VB
Imports Geometry
Dim area = Shapes.CircleArea(2.0)

Rules to keep in mind: only public types cross the boundary; C# names are case-sensitive, so a C# library may expose Name and name as different members, which VB cannot tell apart (a CLS compliance warning exists for this); and C# features VB lacks (such as ref returns or some pattern types) may be unusable from VB. Writing libraries in a CLS-compliant way (<Assembly: CLSCompliant(True)>) keeps them friendly to every language.

P/Invoke: calling native functions

Platform Invoke declares a native function so you can call it like a method.

VB
Imports System.Runtime.InteropServices

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

    <DllImport("kernel32.dll")>
    Function GetTickCount64() As ULong
    End Function
End Module

Dim uptimeMs = NativeMethods.GetTickCount64()

The runtime loads the DLL when the function is first called and marshals arguments: converts .NET values into the native layout. Important details:

Concern Guidance
Strings Choose CharSet.Unicode for "W" APIs; never rely on the default
Integers Match sizes exactly: Win32 DWORD is UInteger, HANDLE is IntPtr, BOOL is Integer (or Boolean with MarshalAs)
Structures Mark with <StructLayout(LayoutKind.Sequential)> and match field order
Errors SetLastError:=True, then Marshal.GetLastWin32Error()
Memory Free native memory with the API that allocated it

Mistakes here do not throw tidy exceptions; they corrupt memory or crash the process, so keep P/Invoke wrappers small and tested.

The same mechanism works on Linux and macOS with the C library. The block below declares getpid from libc, the way you would declare a Windows function, and also shows a struct round trip through unmanaged memory.

C# DllImport and marshaling (C# stand-in on Linux libc)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Modern .NET also offers [LibraryImport], a source generator that produces the marshaling code at compile time (faster, trimmable, AOT-friendly). It is a C# feature; VB projects keep using Declare or DllImport.

VB's older alternative is the Declare statement:

VB
Declare Auto Function GetTickCount64 Lib "kernel32" () As ULong

COM and Office automation

COM (Component Object Model) is the older Windows component technology behind Office, many scanners and drivers. A .NET program talks to COM objects through a generated interop assembly (Visual Studio adds it when you reference the COM library) or, in VB, through late binding.

VB
' Early bound: needs a reference to Microsoft.Office.Interop.Excel
Dim app As New Microsoft.Office.Interop.Excel.Application()
Dim book = app.Workbooks.Add()
Dim sheet = CType(book.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)
sheet.Range("A1").Value = "Hello"
book.SaveAs("hello.xlsx")
book.Close()
app.Quit()

COM objects hold unmanaged resources, so quit the application and release objects with Marshal.ReleaseComObject (otherwise an invisible EXCEL.EXE may linger). Office must be installed on the machine, and server-side Office automation is unsupported by Microsoft. For plain spreadsheets prefer a library that writes .xlsx files directly.

Late binding

With Option Strict Off, VB can call members it cannot verify at compile time; the call is resolved at run time:

VB
Option Strict Off
Dim app As Object = CreateObject("Excel.Application")
app.Visible = True

It is convenient and fragile: typos become run-time errors. Under Option Strict On you write the late call with CallByName or reflection. The stand-in shows run-time member lookup.

C# Late binding by name with reflection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Exposing .NET to others

You can also call into .NET: make a class COM-visible (<ComVisible(True)>) so scripts and legacy VB6/VBA code can use it, publish a native-callable DLL with Native AOT (C#), or expose the logic as a small HTTP service that any language can call. The last option is usually the cleanest; see migrating to modern .NET.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does P/Invoke let you do?

    Platform Invoke declares native functions and marshals arguments.
  2. 2. Which CharSet should you normally choose for Windows 'W' APIs?

    Unicode matches the UTF-16 'W' entry points.
  3. 3. Why call Marshal.ReleaseComObject after Office automation?

    Unreleased COM references can keep the Office process alive.
  4. 4. What is the main risk of late binding?

    Member names are not checked until the call executes.

Summary

  • .NET-to-.NET interop is just a project or assembly reference; keep public APIs CLS-friendly.
  • P/Invoke (DllImport/Declare) calls native code; sizes, strings and structs must match exactly.
  • COM and Office use interop assemblies or late binding; release COM objects and prefer file libraries for spreadsheets.
  • Isolating risky native or COM code in a small wrapper keeps the rest of the program safe.

Next: Migrating to Modern .NET