Skip to content

Foreign Interop

Buntos edited this page Dec 5, 2026 · 1 revision

Foreign Interop

H provides direct zero-overhead interoperability with C-ABI languages (extern "C") and dedicated runtime bridges for C++, GC-enabled D (druntime), Objective-C (libobjc), and .NET (C# and F# via CoreCLR hostfxr or NativeAOT).


1. Direct extern "C" ABI

extern "C" declarations bind directly to C symbols exported by C, Zig, Rust (extern "C"), V (@[export]), D (-betterC), or NativeAOT libraries.

Syntax

# Basic and variadic C declarations
extern "C" def printf(fmt: Ptr[U8], ...) -> I32

# Local H alias mapped to an explicit C symbol name
extern "C" def c_strlen(s: Ptr[U8]) -> Usize = "strlen"
extern "C" def c_fopen(path: Ptr[U8], mode: Ptr[U8]) -> Ptr[Void]? = "fopen"

ABI Rules & Type Mapping

H Type C Equivalent Notes
I8, I16, I32, I64 int8_t, int16_t, int32_t, int64_t Exact width
U8, U16, U32, U64, Usize uint8_t, uint16_t, uint32_t, uint64_t, size_t Exact width
F32, F64 float, double IEEE-754
Bool bool (_Bool) 1-bit LLVM i1
Ptr[T] / Ptr[T]? T* (non-null / nullable) Single 8-byte pointer (NPO for Ptr[T]?)
Ptr[Void] / Ptr[Void]? void* Opaque handle
@[repr(C)] struct S struct S Preserves field declaration order and natural C alignment
@[nogc] Fn(A) -> R R (*)(A) Raw C function pointer; Fn params in extern "C" default to raw function pointers
Plain literal "fmt\n" const char* Implicitly coerces to .rodata Ptr[U8] at compile time
Dynamic String s.cstr (const char*) O(1) extraction of NUL-terminated base pointer while s stays live

All extern "C" functions are callable inside @[nogc] H functions without triggering GC checks.

Linking Foreign Objects & Libraries

Pass object files (.o), static archives (.a), library search paths (-L<dir>), and shared/static libraries (-l<lib>) directly to hlc-pure (or via libs in h.toml):

./zig-out/bin/hlc-pure main.hl my_c_lib.o -L/usr/local/lib -lz -o app

2. C++ Interop (hl-bindgen-cpp)

C++ classes, templates, and exceptions cannot be called directly across a plain C ABI without handling name mangling, this pointers, and stack unwinding. The pure-H tool tools/hl_bindgen_cpp.hl (zig-out/bin/hl-bindgen-cpp) parses a C++ header and generates:

  1. A C++17 extern "C" shim (.cpp) wrapping constructors, destructors, public methods, and template instantiations inside exception-catching guards.
  2. An idiomatic H binding module (.hl) with extern "C" bindings, error inspection helpers, and wrapper classes.

Header Directives & CLI Usage

Annotate C++ template functions with // @hl-instantiate fn_name<cpp_type> comments (or pass --inst fn_name:cpp_type on the command line):

// examples/cpp_interop/counter.hpp
// @hl-instantiate cpp_clamp<int64_t>
// @hl-instantiate cpp_clamp<double>
template <typename T>
T cpp_clamp(T val, T lo, T hi) {
  if (val < lo) return lo;
  if (val > hi) return hi;
  return val;
}

class Counter {
public:
  Counter(int64_t initial) : value_(initial) {}
  int64_t add(int64_t delta);
  int64_t value() const;
  void reset();
private:
  int64_t value_;
};

Generate the shim and bindings, compile the C++ shim, and link with -lstdc++:

./zig-out/bin/hl-bindgen-cpp examples/cpp_interop/counter.hpp \
  --out-cpp counter_shim.cpp \
  --out-hl examples/cpp_interop/counter_bind.hl

g++ -std=c++17 -O2 -I. -c counter_shim.cpp -o counter_shim.o

./zig-out/bin/hlc-pure run examples/cpp_interop/main.hl counter_shim.o -lstdc++

Exception Boundary Architecture

Every generated extern "C" C++ wrapper clears a thread_local std::string g_hl_cpp_err on entry and catches const std::exception& so C++ exceptions never unwind across the C ABI boundary:

  • On exception, e.what() is captured in g_hl_cpp_err and the wrapper returns a safe zero/null sentinel (0, 0.0, false, or nullptr).
  • The generated H module exposes last_error() -> String? (wrapping hl_cpp_last_error) and clear_error() -> Void (wrapping hl_cpp_clear_error).
  • Each C++ class Foo generates Foo_new, Foo_delete, Foo_<method>, and an H wrapper class Foo holding raw: Ptr[Void] with initialize(...), forwarding methods, and destroy() (pair with defer obj.destroy()).

C++ Type Mapping

C++ Type H Type Template Suffix
void Void —
bool Bool bool
int, int32_t I32 i32
long, long long, int64_t I64 i64
unsigned int, uint32_t U32 u32
uint64_t, size_t U64 u64
float F32 f32
double F64 f64
const char*, char* Ptr[U8] ptr
Other pointers / opaque types Ptr[Void] ptr

3. Full D Runtime Bridge (std/interop/druntime)

D code compiled with -betterC links directly via extern "C". When linking GC-enabled D modules that allocate D classes, slices, or std.conv strings, H and D run separate garbage collectors (Boehm GC and D's druntime GC). std/interop/druntime coordinates their lifecycles and prevents the D GC from collecting D objects referenced only from H.

API (std/interop/druntime.hl)

  • @[nogc] init() -> Bool — initializes druntime (rt_init() != 0)
  • @[nogc] term() -> Bool — shuts down druntime (rt_term() != 0)
  • @[nogc] gc_add_root(ptr: Ptr[Void]) -> Void — pins a D heap object in D's GC root set (gc_addRoot)
  • @[nogc] gc_remove_root(ptr: Ptr[Void]) -> Void — unpins a D heap object (gc_removeRoot)
  • @[nogc] gc_collect() -> Void — triggers a D garbage collection (gc_collect)
  • class DRootPin — RAII-style wrapper calling gc_addRoot in initialize(@ptr) and exposing unpin() (pair with defer pin.unpin())

Example Workflow

import "std/interop/druntime" as druntime

extern "C" def d_account_new(name: Ptr[U8], initial: I64) -> Ptr[Void]
extern "C" def d_account_deposit(acct: Ptr[Void], amount: I64) -> I64
extern "C" def d_account_summary(acct: Ptr[Void]) -> Ptr[U8]

def main() -> I32
  if !druntime.init()
    return 1
  end
  defer druntime.term()

  acct = d_account_new("Ada", 100)
  pin = DRootPin.new(acct)
  defer pin.unpin()

  _ = d_account_deposit(acct, 45)
  druntime.gc_collect()
  bal = d_account_deposit(acct, 55)
  puts("#{String.from_cstr(d_account_summary(acct))} bal=#{bal}")
  0
end

Compile and link with LDC (ldc2):

ldc2 -c -O2 -relocation-model=pic examples/d_interop/greeter.d -of=greeter.o
./zig-out/bin/hlc-pure run examples/d_interop/main.hl greeter.o \
  -lphobos2-ldc-shared -ldruntime-ldc-shared

4. Objective-C Runtime Bridge (std/interop/objc)

std/interop/objc binds directly to the cross-platform Objective-C runtime (libobjc / GNUstep libobjc2 on Linux and Windows, libobjc.A.dylib on macOS). It supports both sending messages to existing Objective-C classes and registering new Objective-C classes whose method implementations (IMP) are @[nogc] H functions.

API (std/interop/objc.hl)

All functions except class_name are @[nogc]:

  • Class & selector lookup: get_class(name), lookup_class(name), sel(name) (sel_registerName), class_name(obj) -> String
  • Dynamic class construction:
    • allocate_class_pair(super_cls: Ptr[Void]?, name: Ptr[U8], extra: Usize) -> Ptr[Void]?
    • add_method(cls: Ptr[Void], selector: Ptr[Void], imp: Ptr[Void], types: Ptr[U8]) -> Bool
    • register_class_pair(cls: Ptr[Void]) -> Void
  • Instance lifecycle & ivars:
    • create_instance(cls: Ptr[Void], extra_bytes: Usize) -> Ptr[Void]?
    • indexed_ivars(obj: Ptr[Void]) -> Ptr[Void]
    • dispose(obj: Ptr[Void]) -> Void
  • Dynamic message dispatch:
    • msg_lookup(obj: Ptr[Void], selector: Ptr[Void]) -> Ptr[Void] (objc_msg_lookup)
    • Typed helpers resolving selector + objc_msg_lookup + .as_fn[@[nogc] Fn(...)]() dispatch:
      • send_void(obj, sel_name)
      • send_void_i64(obj, sel_name, a0)
      • send_i64(obj, sel_name) -> I64
      • send_i64_1(obj, sel_name, a0) -> I64
      • send_i64_2(obj, sel_name, a0, a1) -> I64
      • send_cstr(obj, sel_name) -> Ptr[U8]

Registering a @[nogc] H function as an Objective-C IMP uses (&imp_fn).as_ptr[Void]() with the Objective-C type encoding string (e.g. "q@:q" for I64 (id, SEL, I64)).

Build and run:

./zig-out/bin/hlc-pure run examples/objc_interop/main.hl -lobjc

5. .NET Interop — C# & F# (std/interop/dotnet)

H supports two integration models for .NET assemblies:

  1. NativeAOT ([UnmanagedCallersOnly]): Compile a C# or F# library with .NET NativeAOT into a native shared/static library and call its exported symbols directly via extern "C".
  2. Dynamic CoreCLR Hosting (std/interop/dotnet + -lhostfxr): Host the CoreCLR runtime inside an H process using libhostfxr, load .dll assemblies at runtime, and invoke both [UnmanagedCallersOnly] methods and managed delegate methods.

CoreCLR Hosting API (std/interop/dotnet.hl)

  • open(runtime_config_path: String) -> DotNetHost? — initializes CoreCLR from a .runtimeconfig.json file (tries /usr/share/dotnet then system default) and acquires the hdt_load_assembly_and_get_function_pointer (delegate type 5) loader.
  • open_with_root(runtime_config_path: String, dotnet_root: String?) -> DotNetHost? — explicit dotnet_root via @[repr(C)] struct HostfxrInitParams.
  • class DotNetHost:
    • get_unmanaged_fn(assembly_path, type_name, method_name) -> Ptr[Void]? — resolves a C# [UnmanagedCallersOnly] method by passing the UNMANAGEDCALLERSONLY_METHOD ((const char*)-1) sentinel.
    • get_delegate_fn(assembly_path, type_name, method_name, delegate_type_name) -> Ptr[Void]? — resolves a managed method matching a named .NET delegate type (ideal for F# modules).
    • close() -> Void — shuts down the hostfxr context via hostfxr_close (pair with defer host.close()).

Cast returned pointers into callable H raw function pointers with .as_fn[@[nogc] Fn(...) -> R]():

add_mul_p = host.get_unmanaged_fn(cs_dll, "HlDotNet.MathOps, CSharpLib", "AddMul")
if add_mul_p != nil
  add_mul = add_mul_p.as_fn[@[nogc] Fn(I64, I64, I64) -> I64]()
  result = add_mul(3, 4, 6)
end

F# Discriminated Union Projection

F# discriminated unions project cleanly across the C ABI using a sequential struct ([<Struct; StructLayout(LayoutKind.Sequential)>]) paired with an identical @[repr(C)] struct and payload enum in H (see examples/dotnet_interop/FSharpBridge.fs and examples/dotnet_interop/main.hl):

@[repr(C)]
struct FsShape
  tag: I32
  a: F64
  b: F64
end

enum Shape
  circle(F64)
  rect(F64, F64)
end

Link the H host executable against -lhostfxr:

./zig-out/bin/hlc-pure examples/dotnet_interop/main.hl -lhostfxr -o dotnet_demo
./dotnet_demo examples/dotnet_interop/hl_dotnet.runtimeconfig.json CSharpLib.dll FSharpBridge.dll

Next: Tooling and LSP

Clone this wiki locally