简体   繁体   中英

Marshal wchar_t** from C++ to C# as an out parameter?

I have this function in a dll in C and I cannot change it:

extern "C" SIBIO_MULTILANGUAGE_API_C DWORD getLabel(const char* const i_formName, 
                                                    const char* const i_fieldName, 
                                                    wchar_t** i_output);

I know that this call inside allocates the memory for the wchar_t* using the function CoTaskMemAlloc .

In C# I wrapped this function in this way:

[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;
}

I'm able to read correctly the content of the wchar_t* but reading in this way I don't free the memory allocated in the C function.

How can I read the wchar_t* and also be able to free it? Any help is greatly appreciated!

Thanks to @Dai and @IanAbbot comments I've come up to a solution that works perfectly:

 [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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM