Return contents of a std::wstring from C++ into C#

前端 未结 2 1383
时光说笑
时光说笑 2020-12-03 19:43

I have an unmanaged C++ DLL that I have wrapped with a simple C interface so I can call PInvoke on it from C#. Here is an example method in the C wrapper:

co         


        
2条回答
  •  不思量自难忘°
    2020-12-03 20:40

    You are going to have to rewrite your getMyString function for the reasons mentioned in Hans Passant's answer.

    You need to have the C# code pass a buffer in to your C++ code. That way the your code (ok, the CLR Marshaller) controls the lifetime of the buffer and you don't get into any undefined behavior.

    Below is an implementation:

    C++

    void getMyString(wchar_t *str, int len)
    {
        wcscpy_s(str, len, someWideString.c_str());
    }
    

    C#

    [DllImport( "my.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode )]
    private static extern void GetMyString(StringBuffer str, int len);
    public string GetMyStringMarshal()
    {
        StringBuffer buffer = new StringBuffer(255);
        GetMyString(buffer, buffer.Capacity);
        return buffer.ToString();
    }
    

提交回复
热议问题