Skip to content

Bug! Marshal.GetDelegateForFunctionPoiner returns wrong delegate #9074

@dmitriyse

Description

@dmitriyse

OS: Windows 10 x64, Ubuntu 16.04 x64
Framework: NetCoreApp 2.0, Net Framework 4.6

Given code:

using System;
using System.Runtime.InteropServices;

namespace MarshalDelegateError
{
    public class Test1
    {
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate IntPtr MyDelegateOne(IntPtr a, IntPtr b, IntPtr c);
    }

    public class Test2
    {
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate IntPtr MyDelegateTwo(IntPtr a, IntPtr b, IntPtr c);
    }

    class Program
    {
        private static IntPtr MyTestFunc(IntPtr a, IntPtr b, IntPtr c)
        {
            return a;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            IntPtr ptr = Marshal.GetFunctionPointerForDelegate((Test1.MyDelegateOne)MyTestFunc);

            var d1 =(Test1.MyDelegateOne) Marshal.GetDelegateForFunctionPointer(ptr, typeof(Test1.MyDelegateOne));
            var d2 = (Test2.MyDelegateTwo)Marshal.GetDelegateForFunctionPointer(ptr, typeof(Test2.MyDelegateTwo));
            Console.WriteLine("Bug was not reproduced!");
        }
    }
}

Produces this error:
image

But should works fine.

This problem forces developer to manually maintain strong one to one relationship between marshaling delegate name and marshaling delegate signature.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions