Skip to content

Cross platform PInvoke - returning strings to .NET core 2.0 #10748

@MattWorkWeb

Description

@MattWorkWeb

I need to have my C++ dll return a string to .NET core 2.0 wrapper. I want .NET to free up string when appropriate, and not have to make explicit call back to C++ to deallocate string. I've been able to do this successfully if I use CoTaskMemAlloc() (in Windows) to allocate the memory for string on C++ side but CoTaskMemAlloc is not supported in Linux. Windows C++ solution with CoTaskMemAlloc:

[.NET code]
[DllImport(EngineDllFullPath, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string getText();

    public static string GetValue()
    {
        string s = getText();  // No need to free; .NET will take care of it
        return s;
    }

[Unmanaged C++ code]
char* getText()
{
...
char* s = (char*)::CoTaskMemAlloc(size);
...
return s;
}

Is there a cross platform solution to this that doesn't use CoTaskMemAlloc that can compile/run on windows and linux?

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Interop-coreclrquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions