アウトプットブログ

勉強したことをまとめていきます。

DPI-CでSystemVerilogからC言語の関数呼び出し

VHDL/SystemVerilog混在シミュレーションにてSystemVerilogテストベンチからVHDLモジュールを呼び出せたので、次はDPI-CでC言語関数の生成データをVHDLモジュールに入力してみる。

C言語コンパイルできる環境が必要なため、MinGWをインストール、環境設定した。
MinGWのインストールと使い方(2014年版) | Pa-kun plus idea

ソースは以下の通り。記述方法(と後のコンパイル方法)はこちらを参考にさせて頂いた。
ModelSimASE+clangでSystemVerilog DPI-Cをシミュレーションする - Qiita
hoge_c.c

#include <stdio.h>
#include "svdpi.h"  // DPI-Cを使用するためのインクルードファイル

char data = 0;

char hoge_c ()
{
    data = data + 1;
    
    return data;
}

hoge_sv.sv

timeunit 1ns;
timeprecision 10ps;

module hoge_sv();
    // C関数をインポート
    import "DPI-C" function byte hoge_c();
    
    // クロック
    bit clk_i = 1'b0;
    always begin
        #5ns clk_i = ~clk_i;
    end
    
    // リセット
    bit srst_i;
    initial begin
        srst_i = 1'b1;
        #100ns;
        @(posedge clk_i) #1ps srst_i = 1'b0;
    end
    
    // インクリメントデータをC関数を使用して生成
    byte d_i;
    
    always @(posedge clk_i) begin
        if (srst_i) begin
            d_i = 8'h00;
        end else begin
            d_i = hoge_c();
        end
    end
    
    byte d_o;
    
    // d_o = d_i + d_i
    hoge_vhd u_vhd (
        .srst_i(srst_i),    //: in  std_logic;
        .clk_i(clk_i),      //: in  std_logic;
        
        .d_i(d_i),          //: in  std_logic_vector (7 downto 0);
        .d_o(d_o)           //: out std_logic_vector (7 downto 0)
    );
endmodule

hoge_vhd.vhd

library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity hoge_vhd is
    port (
        srst_i  :   in  std_logic;
        clk_i   :   in  std_logic;
        
        d_i     :   in  std_logic_vector (7 downto 0);
        d_o     :   out std_logic_vector (7 downto 0)
    );
end hoge_vhd;

architecture rtl of hoge_vhd is

begin

process (clk_i) begin
    if (rising_edge(clk_i)) then
        if (srst_i = '1') then
            d_o <= (others => '0');
        else
            d_o <= d_i + d_i;
        end if;
    end if;
end process;

end rtl;

コンパイルからシミュレーションまでModelSimのTranscriptウィンドウから実行可能。コマンドをtclにまとめた。実行コマンドは"source hoge_tcl.tcl"となる。
hoge_tcl.tcl

vlib work
vlog -dpiheader dpiheader.h hoge_sv.sv -sv
vcom *.vhd
gcc -c -IC:/altera/15.1/modelsim_ase/include hoge_c.c
gcc -shared -Bsymbolic -o hoge_c.dll hoge_c.o
vsim -sv_lib hoge_c hoge_sv

シミュレーション結果を示す。C関数にて生成したデータをVHDLモジュールにて使用できた。
f:id:HappyField:20151122023221p:plain

尚、Cソースを再コンパイルする場合にはシミュレーションを終了させる必要があった。シミュレーション実行時にCのDLLとリンクしているためと思われる。