Example of passing a static array of bytes from SystemVerilog to C via DPI

Could somebody post an example for reference? I am not able to find any from the forum.
Thanks.

In reply to dnguyen82us:

Can you show the SystemVerilog code which will be calling the DPI? And what does the C function look like which will be processing the data?

In reply to cgales:


module SV_monitor;
   byte packet_data [2048];
   task pass_2_C ();
      // passing packet_data array to a C function
   endtask
endmdule

// I think the C function would have parameters length, handle and then print the array

In reply to dnguyen82us:

Here is some code to get started. Refer to the LRM for all the DPI related functions available for array information. Also, most simulators will generate DPI headers for C/C++ code, so you can ensure that your function prototypes match.

sv_monitor.sv


import "DPI-C" function void dpi_monitor(byte data[]);

module sv_monitor();
  byte packet_data[2048];

  initial begin
      dpi_monitor(packet_data);
  end
endmodule

header.h

#ifndef INCLUDED_HEADER
#define INCLUDED_HEADER

#ifdef __cplusplus
#define DPI_LINK_DECL  extern "C" 
#else
#define DPI_LINK_DECL 
#endif

#include "svdpi.h"

DPI_LINK_DECL DPI_DLLESPEC
void
dpi_monitor(
    const svOpenArrayHandle data);

#endif

dpi.c

#include <stdio.h>
#include "header.h"

void dpi_monitor(const svOpenArrayHandle data) {
    int size;
    int dimensions;

    dimensions = svDimensions(data);

    printf("Data array has %d dimensions\n", dimensions);

    size = svSize(data, 1);
    
    printf("Data array has %d elements\n", size);
}

In reply to cgales:

How do you get the values of data [idx] in C domain? Thanks.

In reply to dnguyen82us:

As I stated in my previous response, you need to refer to the LRM on how to access the array data. Section H.12 provides all the information required on accessing Open arrays.

In reply to cgales:

I implemented the dpi_monitor as the following:


void dpi_monitor (svOpenArrayHandle data) {
    int idx, size;
    unsigned char byte;

    size = svSize (data, 1);

    for (idx = 0; idx < size; idx++) {
        byte = *(unsigned char *) svGetArrElemPtr1 (data, idx); // Extract array elements in C domain
        printf ("data [%0d] = %02x ", idx, byte);
    }
}