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

前端 未结 2 1381
时光说笑
时光说笑 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:24

    You need to specify MarshalAs attribute for the return value:

        [DllImport( "my.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
        [return : MarshalAs(UnmanagedType.LPWStr)]
        private static extern string GetMyString();
    

    Make sure the function is indeed cdecl and that the wstring object is not destroyed when the function returns.

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
提交回复
热议问题