I have C code (predictor model) that can generate an array of variable length as its result. It is unknown before calling the C code what the size of this array is, and there is some amount of randomization involved (noise modelling)
I need to call this C predictor model from SystemVerilog, and get back the output result array.
As a newbie to DPI-C, I ran into 3 limitations:
- The results array on the SV side needs to be allocated prior to calling the C code. Since I do not know what the size will be, I stand the chance of overallocating or underallocating.
- I cannot pass an open array from C -> SV in an export function.
- An export function cannot be used for class methods(!)
To work around this, I created a hacky juggling between the 2 interfaces and global variables/tasks.
I have posted my solution and it works fine, but I would like to know if anyone has a more elegant solution than this. I especially do not like having to use global variables.
SV:
export "DPI-C" function allocate_mem;
export "DPI-C" function set_item;
import "DPI-C" context function void predictForMe (input int noiseA, input int noiseB);
int result[];
function void allocate_mem(int size);
result = new[size];
endfunction
function void set_item(int index, int item);
result[index] = item;
endfunction
class my_class;
// constructor etc etc - assume is valid
// my_func
function void my_func();
int noiseA = 10; // hardcode to simplify example
int noiseB = 20; // hardcode to simplify example
// call imported function
predictForMe( noiseA, noiseB );
endfunction
endclass
C:
extern void allocate_mem(int size);
extern void set_item(int index, int item);
void predictForMe(int noiseA, int noiseB)
{
// do some calcualation based on noiseA and noiseB
// generates an answer_array with num elements = X
allocate_mem(X);
for(i = 0; i < X; i++) set_item(i, answer_array[i]);
}
Any better solutions are welcome.