Invoke “internal extern” constructor using reflections

点点圈 提交于 2019-12-23 05:12:32

问题


I have following class (as seen through reflector)

public class W : IDisposable
{
    public W(string s);
    public W(string s, byte[] data);

    // more constructors

    [MethodImpl(MethodImplOptions.InternalCall)]
    internal extern W(string s, int i);

    public static W Func(string s, int i);

}

I am trying to call "internal extern" constructor or Func using reflections

MethodInfo dynMethod = typeof(W).GetMethod("Func", BindingFlags.Static);                
object[] argVals = new object[] { "hi", 1 };
dynMethod.Invoke(null, argVals);

and

Type type = typeof(W);
Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };
ConstructorInfo dynMethod = type.GetConstructor(BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, argTypes, null);
object[] argVals = new object[] { "hi", 1 };
dynMethod.Invoke(null, argVals);

unfortunantly both variants rise NullReferenceException when trying to Invoke, so, I must be doing something wrong?


回答1:


Using Activator is usually good idea but you have to use a call that has BindingFlags as input parameter to use it for internal constructor.

In you code there are a few of different mistakes. You use wrong BindingFlags in both snippets and in constructor snippet you used wrong Invoke method. Here is code that should work:

MethodInfo dynMethod = typeof(W).GetMethod("Func", BindingFlags.Static | BindingFlags.Public);
object[] argVals = new object[] { "hi", 1 };
dynMethod.Invoke(null, argVals);


Type type = typeof(W);
Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };
ConstructorInfo dynMethod = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, argTypes, null);
object[] argVals = new object[] { "hi", 1 };
dynMethod.Invoke(argVals);

Activator.CreateInstance(typeof(W), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { "hi", 1 }, null);



回答2:


You need to call Activator.CreateInstance:

Activator.CreateInstance(typeof(W), "hi", 1);


来源:https://stackoverflow.com/questions/2654702/invoke-internal-extern-constructor-using-reflections

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!