Я хочу вернуть структуру результата по ссылке, поскольку вызывающий код не может напрямую возвращать структуры из-за к привязке к .NET Framework, которая не имеет возможности возвращать структуры. (https://github.com/dotnet/runtime/issue ... -572207188)
В следующем примере мой вопрос: нужно ли мне освободить память структуры это было передано вручную при реализации метода C++? Или все это делается на стороне управляемого кода (C#)?
C++:
Код: Выделить всё
struct Error
{
char* message = nullptr;
unsigned long code = 0;
};
struct Result
{
bool success = false;
Error error; // can be ignored if success = true
char* content = nullptr; // should be non-nullptr if success = true
};
extern "C" __declspec(dllexport) void CallWithStructRefResult(const char* input, Result& result);
Код: Выделить всё
public readonly record struct Error(string Message, int Code);
public record struct Result
{
[MarshalAs(UnmanagedType.I1)]
public readonly bool Success;
public readonly Error Error;
public readonly string Content;
}
Код: Выделить всё
[DllImport(CppDll, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern Result CallWithStructRefResult([MarshalAs(UnmanagedType.LPUTF8Str)] string input, ref Result result);
Result returnFromCpp = new();
CallWithStructRefResult("someContentToSend", ref result);
Код: Выделить всё
Result res = new Result { Success = false, Error = new(Message: "None", Code: 0), Content = "someLongStringThatMightNeedToBeCleanedUpBeforeCppWritesToIt" };
Подробнее здесь: https://stackoverflow.com/questions/786 ... -reference