Skip to content

P/Invoke function returning SafeSocketHandle throws "System.MissingMethodException: .ctor" #45633

@asmichi

Description

@asmichi

Description

On .NET 5, P/Invoke function returning SafeSocketHandle throws "System.MissingMethodException: .ctor". See MissingSafeSocketHandleCtor.zip for a full repro project.

    public static class Program
    {
        private const int AF_INET = 2;
        private const int SOCK_STREAM = 1;

        public static void Main()
        {
            // System.MissingMethodException: '.ctor'
            // (This returns -1 because we have not initialized WinSock2; that does not matter, though.)
            var sock = socket(AF_INET, SOCK_STREAM, 0);
            sock.Dispose();
        }

        [DllImport("Ws2_32.dll")]
        public static extern SafeSocketHandle socket(int af, int type, int protocol);
    }

Configuration

  • .NET SDK 5.0.100
  • Windows 10 Pro x64 (20H2, 19042.630)

Regression?

Yes. Worked on 3.1.404.

Other information

The SafeHandle doc says "You should also provide a parameterless constructor".

A parameterless ctor is defined in the SafeSocketHandle source file but missing from the released assembly at "C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.0\System.Net.Sockets.dll".

I do not think this is an intended behavior. I do now know the root cause, though.

Stack traces:

Unhandled exception. System.MissingMethodException: .ctor
   at ConsoleAppSafeSocketHandle.WinSock2.socket(Int32 af, Int32 type, Int32 protocol)
   at ConsoleAppSafeSocketHandle.Program.Main()

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions