如何从委托和内部的函数指针调用函数

时间:2019-05-01 02:16:03

标签: c# reflection function-pointers

我有下面的代码,调用带有委托的函数,以及委托内部的函数。但是系统抛出异常“无法封送'返回值':无效的托管/非托管类型组合”。在Marshal.GetDelegateForFunctionPointer中,有人可以帮助解决此问题吗?

namespace hello
{ 
    class test
    { 
        public delegate IPAddress[] DnsFuncDelegate(string message);
        public DnsFuncDelegate dns = null;

        static void Main(string[] args)
        {
            BindingFlags anyType = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            string filePath1 = "I:\\psnet\\System.dll";
            Assembly systemAssembly1 = Assembly.LoadFile(filePath1);
            Type targetMethodClass1 = systemAssembly1.GetType("System.Net.Dns");
            var targetMethodType = new Type[] { typeof(String), };
            MethodInfo target1 = targetMethodClass1.GetMethod("GetHostAddresses", anyType, null, targetMethodType, null);
            RuntimeHelpers.PrepareMethod(target1.MethodHandle);
            IntPtr target1Addr = target1.MethodHandle.GetFunctionPointer();

            DnsFuncDelegate dns = (DnsFuncDelegate)Marshal.GetDelegateForFunctionPointer(target1Addr, typeof(DnsFuncDelegate));

            IPAddress[] addresses2 = dns("localhost");
        }
    }
}

0 个答案:

没有答案