Skip to content

Marshalling strings with certain characters fails when inside a struct #1355

@ducakar

Description

@ducakar

Affected versions: .NET Core 3.1
OS: Arch Linux, Buildroot

Marshalling a struct containing a string field via P/Invoke fails when the string contains certain unicode characters. The following exception is thrown:

Unhandled exception. System.Runtime.InteropServices.COMException (0x8007007A): The data area passed to a system call is too small.
 (0x8007007A)
   at System.StubHelpers.ValueClassMarshaler.ConvertToNative(IntPtr dst, IntPtr src, IntPtr pMT, CleanupWorkListElement& pCleanupWorkList)
   at Program.foo(Label label)
   at Program.Main(String[] args) in /home/davorin/Razvoj/Concepts/Test/Program.cs:line 7

It seems the issue is only triggered when the string contains characters that occupy more than 2 bytes in UTF-16. It doesn't matter whether the struct is passed by value, by pointer or in an array.

Minimal test case:

using System.Runtime.InteropServices;

class Program
{
    static void Main()
    {
        foo(new Label { Text = "●" });
    }

    [DllImport("foo")]
    static extern void foo(Label label);

    [StructLayout(LayoutKind.Sequential)]
    struct Label
    {
        public string Text;
    }
}
// Compile as a shared library:
// gcc -shared -o libfoo.so foo.c

struct Label {
  const char* text;
};

void foo(struct Label label) {
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions