I ended up declaring a function that deallocates memory that was allocated and returned to cpp code earlier.
And my code looks like this:
public static IntPtr GetText()
{
return Marshal.StringToCoTaskMemUni(SomeClass.SomeMethodThatReturnsAString());
}
public static void FreeMemory(IntPtr ptr)
{
Marshal.FreeCoTaskMem(ptr);
}
void OnWriteValue()
{
char16_t const *string = CSharp::GetText();
if (string)
{
Print(string);
CSharp::FreeMemory(string);
}
}
Thanks for your answers.