Call the constructor "internal extern" using reflections

I have the following class (as shown through a 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 the constructor "internal extern" 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);

unfortunately, both options raise a NullReferenceException when trying to call, so should I do something wrong?

0
source share
2 answers

Using is Activatorusually a good idea, but you should use a call with BindingFlags as an input parameter in order to use it for an internal constructor.

. BindingFlags , Invoke. , :

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

Activator.CreateInstance:

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

All Articles