DPI malloc( sizeof( TYPE ) )

There are useful C functions that you could use directly via the DPI, if only you could easily allocate memory for the function to operate on.

Just because they are probably familiar, let’s take the POSIX regex functions. The only thing preventing you from using them directly via the DPI, is you need to allocate a regex_t struct.

    import "DPI-C" function chandle malloc( longint unsigned size_t );
    import "DPI-C" function int regcomp( input chandle re, input string str, int cflags=9 ); // extended, nosub
    import "DPI-C" function int regexec( input chandle re, string str, int nmatch=0,longint ptr=0,int eflags=0);

    chandle re;
    initial begin
        re = malloc( 64 );  // HACK platform dependent malloc( sizeof(regex_t) )
        regcomp( re, "regex pattern" );
        if ( 0 == regexec( re, "string" ) )
            $write( " re matched \n" );
        else
            $write( " re did not match \n" );
    end

I’m avoiding creating specialized malloc functions in C.

    import "DPI-C" function chandle malloc_regex_t();

If you can avoid doing that, useful C functions become directly available from SystemVerilog without writing any C code at all. Simply add the import statement and off you go. Right now, my hack is to hard code the actual size in bytes, but I’m wondering if anyone has figured out a clever way to expose the functionality of the sizeof operator?

In reply to warnerrs:

There is no way to pass type information across the language boundary. It’s up to the user to provide matching function prototypes. SystemVerilog compilers can generate C prototypes from your SystemVerilog source code, but no standard C compiler is going to spit out information fro SystemVerilog.

You could write a C routine that generate the source to a package with the required information:

package C_parameters;
   SIZOF_REGEX_T = 64;
endpackage

Then your SystemVerilog code imports that parameter to call a standard malloc.

FYI, most simulators have already implemented string.match() methods directly in SystemVerilog.