網上有些例子只給了簡單的print,文檔裏也只有在module中調用c,c中用module的函數,不能充分說明問題。既然希望在C裏調用C++的函數,那麼肯定要能訪問到C++類裏的變量那纔有意義。這裏給出一個簡單的例子,示例代碼如下:
調用關係:
top call sv_print();
top call c_print();
c_print() call c_print_call();
c_print() call cpp_print();
// top.v
module top;
string s;
c_sv sv_inst;
import "DPI-C" function void c_print(input string s);
initial begin
s = "Hello DPI";
sv_inst = new();
sv_inst.sv_print(s);
c_print(s);
end
endmodule
//c_dpi.c
void c_print(const char* s) {
c_print_call(s);
cpp_print(s);
}
//c_dpi_call.c
#include <stdio.h>
void c_print_call(const char* s) {
printf("C:\t%0s\n", s);
}
//cpp_dpi.cpp
#include <stdio.h>
#include <iostream>
#ifdef __cplusplus
extern "C" {
#endif
class c_cpp{
public:
c_cpp();
~c_cpp();
char* get_string();
private:
char* prefix;
};
void cpp_print(char* s);
#ifdef __cplusplus
}
#endif
using namespace std;
c_cpp::c_cpp() {
prefix = "CPP:\t";
}
c_cpp::~c_cpp(){
}
char* c_cpp::get_string(){
return prefix;
}
void cpp_print(char* s) {
c_cpp inst;
char* prefix;
prefix = inst.get_string();
cout << prefix << s << endl;
}
//sv_dpi.sv
class c_sv;
function new();
endfunction : new
function void sv_print(string s);
$display("SV:\t%0s", s);
endfunction : sv_print
endclass
相較c調用c++, c++調用c會簡單很多,詳情請查看參考文獻2.
參考文獻:
1. SystemVerilog DPI (Direct Programming Interface) VCS 2006.06-SP2-2 by:Synopsys, Inc.
2. C++項目中的extern ”C“ {}by:吳秦