Passing a String Array from C (C++) into SV using DPI

I’m trying to pass an array of strings from a DPI function into SystemVerilog in Questa. I have created a simple testcase to experiment with. I can successfully assign string literals to the pointers returned by svGetArrElemPtr1, but if I try to strcpy to them, I get segfaults (see commented lines in the C code). Any suggestions on the correct way to do this?

C++ Code:

#include <iostream>
#include <svdpi.h>
#include <string>

using namespace std;

extern "C" void strtest(
  svOpenArrayHandle a  // String Array Output
) {

    *(char **)svGetArrElemPtr1(a,0) = "Hello";
    *(char **)svGetArrElemPtr1(a,1) = "out";
    *(char **)svGetArrElemPtr1(a,2) = "there";

//   const char *mystr = "there";
//   strcpy(*(char **)svGetArrElemPtr1(a,count), mystr);
}


SystemVerilog Code:

module strtest_tb;

import "DPI-C" function void strtest(
  output string outbuf[]
);

string str_out[5];

initial begin
  strtest(str_out);
  for (int i=0; i<3; i++) begin
    $display("OUTPUT STRING[%d]:%s", i,str_out[i]);
  end
  $stop;
end

endmodule

It looks like I just needed to allocate on the C++ side.

*(char **)svGetArrElemPtr1(a,2) = new char[100];
   const char *mystr = "there";
   strcpy(*(char **)svGetArrElemPtr1(a,2), mystr);

Problem appears to be solved.

In reply to mbehrin:

Thanks for the solution.
I have a similar problem where i want to write string data to a structure instead of an array. Could you please let me know the way to handle that in both sv and c ?

In reply to Prajwal hegde:

module top;
   typedef struct {string s1,s2;} st;
   import "DPI-C" function void test (output st a);
   st s; 
   initial begin
      test(s);
      $display("%p",s);
   end
endmodule
#include "dpiheader.h"
extern "C" void test ( st* a ) {
  a->s1 = "Hello";
  a->s2 = "World";
  const char *mystr = "there";
  *(char **)&a->s2 = new char [10];
  strcpy(*(char **)&a->s2, mystr);

}