有的時候需要交互struct,union數據類型,下面舉個簡單例子。
在SV裏定義這個一個結構體:
typedef struct {
int id;
string name;
} xaction;
同樣的,在C裏定義同樣的結構體,結構體名可以不一致:
typedef struct {
int id;
char* name;
} c_xaction;
下面把這個結構體傳遞給C,讓C打印出來,SV中做好接口:
import "DPI-C" function void c_print(input xaction x);
void c_print (c_xaction* x) {
printf("id = %0d, name = %s\n", x->id, x->name);
}
這裏需要注意很重要的一點,SV中的形參類型是xaction, 而C中的形參類型是結構體指針,不可以搞錯。
xaction x;
x.id = 2;
x.name = "abc";
c_print(x);
打印出:id = 2, name = abc
下面再來看看union的情形,DPI只能傳遞packed union, 不熟悉packed概念的請參考SV LRM IEEE1800.
SV:
typedef union packed{ int i; bit[31:0] f; } num;
C:
typedef union { int i; float f; } num;
這時和struct一樣,C中的形參只能爲指針類型。這裏取個巧,把第二個數做成float類型。在sv中賦值:
n.i = 32'h3FFF_FFFF;
這時在C中printf n.f會得到2.000000.注意高低位
struct中套struct可以支持,只要是packed類型就可以,但是注意struct指定位寬是用不了DPI的:
typedef struct {
int n0 : 10 ;
int n1 : 6;
} invalid_xaction;