Skip to content

possible correction regarding marshaling #48785

@ophura

Description

@ophura

Type of issue

Outdated article

Description

I considered changes, regarding the first code block, here's what I had in mind:

using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;

internal static partial class Interop
{
    [LibraryImport("SomeNativeLibrary.dll")]
    internal static partial int MethodA([MarshalAs(UnmanagedType.LPStr)] string parameter);

    // or

    [LibraryImport("SomeNativeLibrary.dll")]
    internal static partial int MethodB([MarshalAs(UnmanagedType.LPUTF8Str)] string parameter);

    // or

    [LibraryImport("SomeNativeLibrary.dll")]
    internal static partial int MethodC([MarshalUsing(typeof(Utf8StringMarshaller))] string parameter);

    // or

    [LibraryImport("SomeNativeLibrary.dll", StringMarshalling = StringMarshalling.Utf8)]
    internal static partial int MethodD(string parameter);
}

this is to complete the set of options originally proposed. I'd also like to note that one of the originally suggested approaches behaves differently in semantics, and that is UnmanagedType.LPStr; which relies on AnsiStringMarshaller, whereas the others use Utf8StringMarshaller for marshaling.

that is worrisome to me since the documentation states that:

if you want the string to be sent as a null-terminated UTF-8 string, you could do it like this:

followed by the code block, which again, the first method in it uses the AnsiStringMarshaller...
should MethodA be excluded in this case?

Page URL

https://learn.microsoft.com/en-us/dotnet/standard/native-interop/type-marshalling

Content source URL

https://github.com/dotnet/docs/blob/main/docs/standard/native-interop/type-marshalling.md

Document Version Independent Id

ea959c7a-ad3b-395d-721b-ccb4ffcb9d82

Platform Id

e7bef02c-c8cb-d334-32fc-31f3917514e7

Article author

@jkoritzinsky

Metadata

  • ID: 98dbfdf5-7870-b887-fece-a992ef191a46
  • PlatformId: e7bef02c-c8cb-d334-32fc-31f3917514e7
  • Service: dotnet-fundamentals

Related Issues

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions