Calling C++ function from C#

女生的网名这么多〃 提交于 2019-12-10 16:34:37

问题


I have a 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


回答1:


With P/Invoke.




回答2:


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);
      }
   }

}



来源:https://stackoverflow.com/questions/1041160/calling-c-function-from-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!