Skip to content

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

Closed

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

Activity

  1. jkotas commented on Jul 23, 2018

    @jkotas
    Member
  2. AaronRobinsonMSFT commented on Jul 23, 2018

    @AaronRobinsonMSFT
    Member
  3. AaronRobinsonMSFT commented on Jul 23, 2018

    @AaronRobinsonMSFT
    Member

    @MattWorkWeb I have created an issue for documenting or creating an example for this. See dotnet/coreclr#19090.

  4. AaronRobinsonMSFT commented on Jul 23, 2018

    @AaronRobinsonMSFT
    Member
  5. added a commit that references this issue on Nov 15, 2019
  6. transferred this issue fromdotnet/coreclron Jan 31, 2020
  7. ghost locked as resolved and limited conversation to collaborators on Dec 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Interop-coreclrquestion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions