How to determine if a ConstructorInfo object has an unmanaged parameter?

My application uses reflection to parse C ++ / cli code at runtime.
I need to determine if the type has a constructor without unmanaged parameters (pointers, etc.), because I want to use later:

ConstructorInfo constructorInfo; // ... var ret = constructorInfo.Invoke(BindingFlags..., null, myParameters, null); 

If the constructor has a pointer to an unmanaged object as a parameter, a cast exception is thrown when I pass it null.

So how do I define this? no IsManaged ... and IsPointer will not help in this case.

+6
source share
2 answers

It's unclear what your problem really is, but here is a small demo program that shows passing null constructor that takes a pointer as an argument and detects it using IsPointer :

 using System; using System.Reflection; namespace pointers { unsafe class Program { public Program(int* x) { Console.WriteLine("It worked!"); } static void Main(string[] args) { ConstructorInfo[] c = typeof(Program).GetConstructors(); c[0].Invoke(BindingFlags.Default, null, new object[] { null }, null); Console.WriteLine(c[0].GetParameters()[0].ParameterType.IsPointer); } } } 

He prints:

  It worked!
 True 
+2
source

Try checking if this parameter is a value type. null not a valid value for any type of value, be it an unmanaged pointer or just int .

-1
source

Source: https://habr.com/ru/post/887541/


All Articles