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

前端 未结 3 1565
粉色の甜心
粉色の甜心 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:44

    A lot of functions that are encountered in the Windows API take string or string-type parameters. The problem with using the string data type for these parameters is that the string datatype in .NET is immutable once created so the StringBuilder datatype is the right choice here. For an example examine the API function GetTempPath()

    Windows API definition

    DWORD WINAPI GetTempPath(
      __in   DWORD nBufferLength,
      __out  LPTSTR lpBuffer
    );
    

    .NET prototype

    [DllImport("kernel32.dll")]
    public static extern uint GetTempPath
    (
    uint nBufferLength, 
    StringBuilder lpBuffer
    );
    

    Usage

    const int maxPathLength = 255;
    StringBuilder tempPath = new StringBuilder(maxPathLength);
    GetTempPath(maxPathLength, tempPath);
    

提交回复
热议问题