[英]How do I marshal wchar_t* from C++ to C# as an out parameter or return value?
[英]Marshal wchar_t** from C++ to C# as an out parameter?
我在C中的dll中具有此功能,但無法更改:
extern "C" SIBIO_MULTILANGUAGE_API_C DWORD getLabel(const char* const i_formName,
const char* const i_fieldName,
wchar_t** i_output);
我知道此調用使用函數CoTaskMemAlloc
為wchar_t*
分配內存。
在C#中,我以這種方式包裝了此函數:
[DllImport("sibio_multilanguage_c.dll", EntryPoint = "getLabel", CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 _getLabel([In] string i_formName, [In] string i_fieldName,
[MarshalAs(UnmanagedType.LPWStr)] out string i_output);
static public string getLabel(string i_formName, string i_fieldName)
{
string str = null;
UInt32 err = _getLabel(i_formName, i_fieldName, out str);
if (0 != err)
{
throw new System.IO.FileNotFoundException();
}
return str;
}
我能夠正確讀取wchar_t*
的內容,但是以這種方式讀取時,我不會釋放C函數中分配的內存。
如何閱讀wchar_t*
並能夠將其釋放? 任何幫助是極大的贊賞!
感謝@Dai和@IanAbbot的評論,我提出了一個完美的解決方案:
[DllImport("sibio_multilanguage_c.dll", EntryPoint = "getLabel", CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 _getLabel([In] string i_formName, [In] string i_fieldName,
out IntPtr i_output);
static public string getLabel(string i_formName, string i_fieldName)
{
IntPtr i_result;
string str = null;
UInt32 err = _getLabel(i_formName, i_fieldName, out i_result);
if (0 != err)
{
throw new System.IO.FileNotFoundException();
}
str = Marshal.PtrToStringAuto(i_result);
Marshal.FreeCoTaskMem(i_result);
return str;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.