【问题标题】:SystemVerilog DPI returning string from C++ to verilog - ASCII charaters at the end?SystemVerilog DPI 从 C++ 返回字符串到 verilog - 最后是 ASCII 字符?
【发布时间】:2015-06-17 22:08:50
【问题描述】:

我正在使用 DPI 从 C 函数向 SystemVerilog 返回一个字符串。

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();
}

在 SystemVerilog 方面:

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

结果: 有时结果是这样的:

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

有时我会明白:

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

我检查了 verilog 端的波形,它们是 NO X 传播。 你能帮我理解为什么会出现这个错误吗?

【问题讨论】:

  • 不相关的评论。 return (char*)ss.str().c_str(); 你 un-const 一个带有强制转换的 const 指针。不要这样做。它几乎总是以糟糕的方式结束。该指针被设为 const 是有原因的。幸运的是,你取消了这个傻瓜,然后将它作为 const 返回。
  • 在主题上,您返回一个指向局部变量内部数据的指针。一旦该字符串流超出范围,所有关于您所指向的指针的赌注都将关闭。建议返回字符串:string print_input_dpi(int w, int h, int p, ......int mtail)return ss.str();

标签: c++ system-verilog system-verilog-dpi


【解决方案1】:

您如此精心构建的字符串流在函数末尾超出范围,并返回到它的来源。这些位正在被重用和覆盖,可能是由 cout 打印所述位,导致损坏。老实说,你走运了。从下周二开始,它可能看起来工作正常,但一周后就崩溃了。

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.

快速修复:

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

【讨论】:

    【解决方案2】:

    字符串流在函数结束时超出范围,相关的内存被覆盖。保持函数与 SV DPI 兼容性的正确修复方法是更改​​字符串流的生命周期:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 2013-12-10
      • 2021-12-13
      • 2012-07-14
      • 1970-01-01
      相关资源
      最近更新 更多