DPI-C import --- Returning string value from C with a "char **var" argument

Hello,
I am trying to use C functions in SV environment.
I successfully compiled and set up all the DPI related things.

The C function I want to use is:


int my_dpi(char *arg, char **ret)
{  printf("DPI Received arg: %s", arg);
   sprintf(*ret,"HELLO");
   return TRUE;
}

In SV i import the function as follows:


import "DPI-C" context function int my_dpi(input string arg, output string ret);

And then I try to use it as follows:


res = my_dpi("in_text", ret);
`uvm_info("DPI DBG", $sformatf("Arg: %s RES: %0d rsp: %s", arg, res, ret), UVM_NONE);

With this setup, i have a runtime failure coming from the DPI (Bad handle reference).

By changing how the C function uses the char **ret, I don’t get the error, but also miss the “ret” value.


int my_dpi(char *arg, char **ret)
{  printf("DPI Received arg: %s", arg);
   ret = "HELLO";
   return TRUE;
}

I looked into compatibility between SV and C types for DPI, but could not find a clear solution for “char **ret”, which is a “pointer to char pointer” if I am not wrong.

Is there a solution to use the original C function?
Maybe I am declaring the DPI with wrong SV types?

Thanks,
Luca

In reply to Luca Iovinella:

Most simulators will generate the correct header file for DPI calls. You can use this header file in your C code to ensure compatibility.

The correct C prototype is:

int my_dpi(const char arg, const char* ret);

Since the second argument is a pointer to a pointer, you need to de-reference it when it’s being assigned:

int my_dpi(const char *arg, const char **ret) {
printf(“DPI Received arg: %s\n”, arg);
*ret = “HELLO”;
return TRUE;
}

You need to ensure that anything returned back to the simulator has a suitable lifetime and isn’t destroyed on the C side as this may result in invalid data being returned.

In reply to cgales:

Ok thanks for the answer.

So there is no way I can keep the “original” C code.
I should adapt it to be properly interfaced with SystemVerilog correct?

I am not so practical on this topics.

Thanks,
Luca