SystemVerilog dpi

SystemVerilog DPI C++

SystemVerilog DPI (Direct Programming Interface) is an interface which can be used to interface SystemVerilog with foreign languages. These Foreign languages can be C, C++, SystemC as well as others.

DPI allows the user to easily call functions of other language from SystemVerilog and to export SystemVerilog functions, so that they can be called in other languages.

Advantage of DPI is,  it allows to make use of the code exists in other languages.

DPI Import and export methods

Import Method

The methods (functions/tasks) implemented in Foreign language can be called from SystemVerilog and such methods are called Import methods.

Export methods

The methods implemented in SystemVerilog can be called from Foreign language such methods are called Export methods.

It is allowed to transfer the data between two languages through arguments passing and return.

DPI Declaration

Import Declaration

import “DPI-C” function int calc_parity (input int a);

Export Declaration

export “DPI-C” my_cfunction = function myfunction;

SystemVerilog DPI Example

Calling C++ method from SystemVerilog file

//----------------------------------------------
// SystemVerilog File
//----------------------------------------------
module dpi_tb;

  import "DPI-C" function void c_method();
  
  initial
  begin
    $display("Before calling C Method");
    c_method();
    $display("After calling C Method");
  end
  
endmodule

//----------------------------------------------
// C++ file
//----------------------------------------------
#include stdio.h
#include stdlib.h

extern "C" void c_method() {

  printf("     Hello World...!\n");

}

Simulator Output

Before calling C Method
[C-Prog]   Hello World...!
After calling C Method

Click to execute on   

Calling SystemVerilog method from C++ file

//----------------------------------------------
// SystemVerilog File
//----------------------------------------------
module dpi_tb;

  export "DPI-C" function sv_method;
  import "DPI-C" context function void c_method();
  
  initial
  begin
    $display("Before calling C Method");
    c_method();
    $display("After calling C Method");
  end
  
  function void sv_method();
    $display("  [SV-Prog]  Hello World...!");
  endfunction
endmodule

//----------------------------------------------
// C++ file
//----------------------------------------------
#include stdio.h
#include iostream
#include svdpi.h

using namespace std;

extern "C" void sv_method();
extern "C" void c_method() {

  printf("  [C-Prog]   Hello World...!\n");
  sv_method();
}

Simulator Output

Before calling C Method
[C-Prog]   Hello World...!
[SV-Prog] Hello World...!
After calling C Method

Click to execute on