Invoke “internal extern” constructor using reflect

2019-06-13 03:05发布

问题:

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);