1. 在Verilog中调用C函数
首先:准备好纯C/C++代码。比如:
#include <iostream>
int helloFromCpp(int a) {
// 0 is 0
// 1 is 1
// 2 is Z
// 3 is X
int a_int = a;
cout << "(C++) a is " << a_int << endl;
return 0;
}
其次:在verilog调用C函数
module automatic test;
import "DPI-C" function int helloFromCpp(int a);
initial run();
task run();
logic a = 1'bx;
$display("a is %0d", a);
helloFromCpp(a);
a = 1;
$display("a is %0d", a);
helloFromCpp(a);
a = 1'bz;
$display("a is %0d", a);
helloFromCpp(a);
endtask
endmodule
注意用import语法将C函数声明一下。
最后编译运行:
vcs -timescale=1ns/1ns +vcs+flush+all +warn=all -sverilog my_dpi.cc
2. 在C代码中调用Verilog的function/task
如果反过来调用就要用到export语法。
首先:verilog中修改如下:
module automatic test;
import "DPI-C" context task helloFromCpp(logic a);
//import "DPI-C" function int helloFromCpp(int a);
export "DPI-C" function adder;
initial run();
function int adder(int a, int b);
return a+b;
endfunction
task run();
logic a = 1'bx;
$display("a is %0d", a);
helloFromCpp(a);
a = 1;
$display("a is %0d", a);
helloFromCpp(a);
a = 1'bz;
$display("a is %0d", a);
helloFromCpp(a);
endtask
endmodule
接着修改C代码
增加adder的定义
extern int adder(int a, int b);
需要注意的是此时Verilog的Import变成了context task。因为c函数里面调用了verilog的function/task。