Search code examples
c#c++stringdllimport

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


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 know some way to send a string from C# to C++ and from C++ to C# ?
(Some sample code would be helpful)


Solution

  • Passing string from C# to C++ should be straightforward - PInvoke will manage the conversion for you.

    Getting a 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!");