Part 7 · Advanced & Integration · Intermediate

DPI-C: Calling C from SystemVerilog

Hub — DPI imports and exports, context calls, open arrays, C reference models, and debugging the SV/C boundary.

Overview

The Direct Programming Interface (DPI) is SystemVerilog's standard mechanism for calling C functions from SV code and calling SV functions back from C — with plain function-call syntax on both sides. No simulator-specific glue, no handle juggling like the older PLI/VPI interfaces: you declare an import "DPI-C" prototype, link a shared object, and call it like any other function.

In production environments DPI carries reference models (a golden C implementation of the algorithm under test), legacy software stacks, file-format codecs, and performance-critical utilities. It is the single most common SV-to-software boundary, and senior DV interviews probe it heavily.

Sub-topics

  1. DPI Imports — import syntax, pure/context qualifiers, type mapping, svdpi.h, a first checksum example.

  2. Exports & Context Calls — letting C call back into SV, scope rules, svSetScope, callback patterns.

  3. Passing Arrays & Structs — open arrays, packed structs, strings, and memory-ownership rules.

  4. C Reference Models — when C models win, wrapper classes, transaction-level model interfaces.

  5. DPI Pitfalls & Debug — linking flow, name issues, threading rules, crash debugging, DPI vs PLI/VPI.

diagram
Legend: [SV] [C]

  THE DPI BOUNDARY

  SystemVerilog side [SV]              C side [C]
  ───────────────────────              ─────────────────────
  import "DPI-C" function              int  checksum(...)      ← SV calls C
       int checksum(...);     ──────►  (compiled to .so)

  export "DPI-C" function              extern int sv_notify(); ← C calls SV
       int sv_notify();        ◄──────  sv_notify() call in C

                 shared object (.so / .dll)
        ┌──────────────────────────────────────┐
        │  compile C  link  simulator loads  │
        │  at elaboration via -sv_lib / -dpi   │
        └──────────────────────────────────────┘

Key takeaways

  • DPI gives plain function-call semantics across the SV/C boundary — no PLI/VPI handle plumbing.

  • Imports bring C into SV; exports let C call back into SV — context rules govern the latter.

  • Most real environments use DPI for reference models; learn the wrapper-class pattern that hides it.