system-verilogsystem-verilog-dpi

Type erasure in SystemVerilog / DPI


Is it possible to cast SystemVerilog struct to some type-erased pointer, like void *?

I need to pass objects of different struct types from SV to C. And I want to have a single DPI function to handle any kind of supported struct.

On SystemVerilog side I have many types:

typedef struct { ... } stype1;
typedef struct { ... } stype2;
typedef struct { ... } stype3;
typedef struct { ... } stype4;

stype1 var1;
stype2 var2;
stype3 var3;
stype4 var4;

On C side I have a single function that accepts any type:

void send_sv_data(const char* type_name, void *ptr);

I've hoped to use it like this on SV side:

send_sv_data("stype1", var1);
send_sv_data("stype2", var2);

And it works in general, with only problem that SystemVerilog does not supports overloading. So I can only declare it for one type:

import "DPI" function void  send_sv_data(string port_name, stype1 data);

I've tried to have chandle as argument:

 import "DPI" function void  send_sv_data(string port_name, chandle data);

But I have not found a way how I cast a variable of struct type to chandle.


Solution

  • There are no pointers, and no casting of pointers in SystemVerilog. The easiest thing to do is pack your SystemVerilog structs into an array of bytes, and unpack them to your C structs.