网上有些例子只给了简单的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 begins = "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 __cplusplusextern "C" {
#endifclass c_cpp{public:c_cpp();~c_cpp();char* get_string();private:char* prefix;}; void cpp_print(char* s);
#ifdef __cplusplus}
#endifusing 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:吴秦