C ++ function call from C #

I have the following C ++ function

void FillAndReturnString(char ** someString) { char sourceString[] = "test"; *someString = new char[5]; memcpy(*someString, sourceString, 5); } 

It is declared as

 extern "C" { __declspec(dllexport) void __cdecl FillAndReturnString(char ** someString); } 

How do I call this function from C #?

thanks

+4
source share
2 answers

With P / Invoke .

+1
source

You need to know that you allocate an unmanaged block of memory in your C ++ function, so it is not possible to pass a managed String or Array object from C # code to a "hold" char array.

One approach is to define the "Delete" function in your own DLL and call it to free memory. On the managed side, you can use IntPtr to temporarily hold a pointer to a 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); } } 

}

+1
source

Source: https://habr.com/ru/post/1286719/


All Articles