You need to know that you're allocating unmanaged memory block in your c++ function, so it will not be possible to pass a managed String or Array object from C# code to 'hold' the char array.
One approach is to define 'Delete' function in your native dll and call it to deallocate the memory. On the managed side, you can use IntPtr structure to temporarily hold a pointer to c++ char array.
// c++ function (modified)
void __cdecl FillAndReturnString(char ** someString)
{
*someString = new char[5];
strcpy_s(*someString, "test", 5); // use safe strcpy
}
void __cdecl DeleteString(char* someString)
{
delete[] someString
}
// c# class
using System;
using System.Runtime.InteropServices;
namespace Example
{
public static class PInvoke
{
[DllImport("YourDllName.dll")]
static extern public void FillAndReturnString(ref IntPtr ptr);
[DllImport("YourDllName.dll")]
static extern public void DeleteString(IntPtr ptr);
}
class Program
{
static void Main(string[] args)
{
IntPtr ptr = IntPtr.Zero;
PInvoke.FillAndReturnString(ref ptr);
String s = Marshal.PtrToStringAnsi(ptr);
Console.WriteLine(s);
PInvoke.Delete(ptr);
}
}
}