Passing a struct which has double pointer from C to SV using DPI

Hi,

I have a struct in C as follows. I am trying to pass this struct from C to SV and printing the values of each element in the struct. I am getting the correct value of “n” in both C and SV. But the 2D array values of “x” in C and SV are not matching. Please find the code snippet. If I try to pass the 2D array variable(“state.x”) alone from C to SV, it is working fine. But when passing the entire struct, it is not. Please let me know if it possible to pass a struct entirely from C to SV.


C:
==
struct state {
  long n;
  unsigned long **x;
};
extern void sv_getstate(struct state *q);

int main() {
  struct state *q;
  :
  :
  sv_getstate(q);
}

SV:
=== 
`define CNT 2
typedef struct {
    longint n;
    longint unsigned x [2*`CNT+1] [`CNT];
} state;

export "DPI-C" function sv_getstate;
import "DPI-C" context function int main(int argc, string argv[2:0]);

function void sv_getstate(input state y);
  $display("y.n is : %0d",y.n);
    for(int i=0;i<=2*y.n;i++) begin
      for(int j=0;j<y.n;j++) begin
        $display("y.x[%0d][%0d] : %0d",i,j,y.x[i][j]);
      end
    end
endfunction

initial begin
 :
 :
 main(....)
end

In reply to karan_18:

You problem is **unsigned long x is the same as unsigned long x[][], which is not the same what is required to match your SystemVerilog prototype as unsigned long x[5][3]. The key difference is in how the size of the data on the call stack get calculated (I’m not a C/C++ expert).

Some tools automatically generate a dpiheader file you can include into your C code that guarantees your function protoypes match at compile time.

In reply to dave_59:

Thanks Dave for your comments. Wrote a function to pass the 2D array(state.x) alone instead of entire struct from C to SV. It is working fine now.