Passing string from C++ to C#

和自甴很熟 提交于 2019-12-01 09:17:17

When marshalling strings across a P/Invoke boundary, it is always good practice to use a MarshalAs attribute with the appropriate string type. I think putting a [MarshalAs(UnmanagedType.BStr)] on the parameter should take care of the problem.

public delegate void callback([MarshalAs(UnmanagedType.BStr)]string str);

This article has an similar example where someone was passing BSTRs between managed and unmanaged code, but he used IntPtr and some methods on the Marshal class. Marshal.PtrToStringBSTR seems most useful here.

C# strings are UTF-16. I would suggest that C# could be expecting an LPWSTR or something similar rather than a BSTR. If you look at the first example posted, he puts the call type as a wchar_t*, not a BSTR.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!