Bug 7127 - PInvoke with parameter a class without StructLayout
Summary: PInvoke with parameter a class without StructLayout
Status: CONFIRMED
Alias: None
Product: Runtime
Classification: Mono
Component: Interop (show other bugs)
Version: unspecified
Hardware: PC Windows
: Normal normal
Target Milestone: Future Cycle (TBD)
Assignee: Bugzilla
URL:
Depends on:
Blocks:
 
Reported: 2012-09-13 04:31 UTC by xanatos
Modified: 2017-07-13 00:10 UTC (History)
3 users (show)

See Also:
Tags:
Is this bug a regression?: ---
Last known good build:


Attachments

Description xanatos 2012-09-13 04:31:57 UTC
Using mono 2.10.8

This:

        class MyClass
        {
            public int x;
            public int y;
            public int z;
        }

        [DllImport("Kernel32.dll", EntryPoint = "RtlZeroMemory", SetLastError = false)]
        static extern void ZeroMemory(MyClass dest, UIntPtr size);

        static void Main(string[] args)
        {
            MyClass test = new MyClass { x = 10, y = 8, z = 6 };
            ZeroMemory(test, (UIntPtr)12);
        }

runs under Windows (I'm using the ZeroMemory method just to give an example, my problem is with a third party library that pinvokes a method passing a class without StructLayout) (I don't know what is really passed to ZeroMemory, because in the end "test" isn't zeroed, but this isn't my problem :-) I don't need to know how the library works, I just want it to work)

Under Mono I get:

Unhandled Exception: System.Runtime.InteropServices.MarshalDirectiveException: Type ConsoleApplication76.Program/MyClass which is passed to unmanaged code must have a StructLayout attribute.
  at (wrapper managed-to-native) ConsoleApplication76.Program:ZeroMemory (ConsoleApplication76.Program/MyClass,uintptr)
  at ConsoleApplication76.Program.Main (System.String[] args)

(just for information, the problem I have is with BerkeleyDB 5.2.36, in libdb_csharpPINVOKE.cs, BerkeleyDB.Internal.libdb_csharpPINVOKE.DB_ENV_api2_internal_set(HandleRef jarg1, DatabaseEnvironment jarg2) )
Comment 1 Rodrigo Kumpera 2017-07-13 00:10:49 UTC
I can reproduce this behavior on dotnet. Here's a complete test:

using System;
using System.Runtime.InteropServices;

public class Driver
{


    class MyClass
    {
        public int x;
        public int y;
        public int z;
    }

    [DllImport("Kernel32.dll", EntryPoint = "RtlZeroMemory", SetLastError = false)]
	   // [DllImport("libc", EntryPoint = "bzero", SetLastError = false)]
    static extern void ZeroMemory(MyClass dest, UIntPtr size);

    static void Main(string[] args)
    {
        MyClass test = new MyClass { x = 10, y = 8, z = 6 };
        ZeroMemory(test, (UIntPtr)12);
		Console.WriteLine ($"{test.x} {test.y} {test.z}");
    }
}

Note You need to log in before you can comment on or make changes to this bug.