How to pass strings from C# to C++ (and from C++ to C#) using DLLImport?

前端 未结 3 1570
粉色の甜心
粉色の甜心 2020-12-03 04:47

I\'ve been trying to send a string to/from C# to/from C++ for a long time but didn\'t manage to get it working yet ...

So my question is simple :
Does anyone kno

3条回答
  •  醉话见心
    2020-12-03 05:50

    Passing string from C# to C++ should be straight forward. PInvoke will manage the conversion for you.

    Geting string from C++ to C# can be done using a StringBuilder. You need to get the length of the string in order to create a buffer of the correct size.

    Here are two examples of a well known Win32 API:

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
     static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
    public static string GetText(IntPtr hWnd)
     {
         // Allocate correct string length first
         int length       = GetWindowTextLength(hWnd);
         StringBuilder sb = new StringBuilder(length + 1);
         GetWindowText(hWnd, sb, sb.Capacity);
         return sb.ToString();
     }
    
    
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
     public static extern bool SetWindowText(IntPtr hwnd, String lpString);
    SetWindowText(Process.GetCurrentProcess().MainWindowHandle, "Amazing!");
    

提交回复
热议问题