SystemVerilog DPI returning string from C++ to verilog - ASCII charaters at the end?

2.1k views Asked by At

I am returning a string from C function to SystemVerilog using DPI.

const char* print_input_dpi(int w, int h, int p, ......int mtail){
std::stringstream ss;

ss<<"w="<<std::hex<<w<<" ";
ss<<"h="<<std::hex<<h<<" ";
ss<<"p="<<std::hex<<p<<" ";
...
ss<<"mtail="<<std::hex<<mtail<<" ";

return (char*)ss.str().c_str();
}

On the SystemVerilog side:

string formatted_string;
always @* begin
  if(en) begin
    formatted_string = print_input_dpi(w,h,p,...mtail)l  
end

...
always @(nededge sclk) begin
   $fdisplayb(log_file, "", formatted_string)
end

Result: sometimes the result is like this:

w=1, h=3f, p=2f, ...mtail=0ã

sometimes i get this:

w=1, h=3f, p=2f, ...mtailº

I checked the waveforms on the verilog side and they is NO X propagation. Can you please help me understand why I get this error.

2

There are 2 answers

0
user4581301 On

The string stream you so lovingly built went out of scope at the end of the function and was returned to the bits from whence it came. Those bits are being reused and overwritten, probably by the cout printing said bits, resulting in corruption. To be honest, you got off lucky. It could have looked like it was working fine and crashed a week from next Tuesday.

const char* print_input_dpi(int w, int h, int p, ......int mtail)
{
    std::stringstream ss; //<< local variable created here.
    ...    
    return (char*)ss.str().c_str();
} // out of scope and destroyed here, so the returned pointer now points to god knows what.

Quick fix:

string print_input_dpi(int w, int h, int p, ......int mtail)
{
    std::stringstream ss; //<< local variable.
    ...    
    return ss.str();
} 
0
David Plumb On

The string stream went out of scope at the end of the function and the associated memory was overwritten. The correct fix that also maintains compatibility of your function with the SV DPI is simply to change the lifetime of the string stream:

std::stringstream ss; // global variable
const char* print_input_dpi(int w, int h, int p, ......int mtail)
{
    ...
    return ss.str().c_str();
}