I am having a dll that I created with some reflection code in it. When I use this dll in any application and call the specific function containing the reflections calls the program crashes, and I get a null reference in the disassembled view in visual studio. However, when commenting out just the reflection calls the program runs fine, but uncommenting results in the same result with crashing the program.
The picture with the disassembled view I am being presented with click here to view
Below the functions I am trying to run.
internal static CreateInstance CreateInstanceByType(Type type)
{
//check constructor
ConstructorInfo ctor = null;
ConstructorInfo[] ctors =
type.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
for (int i = 0; i < ctors.Length; i++)
{
if (ctors[i].GetParameters().Length == 0)
{
ctor = ctors[i];
break;
}
}
if (ctor == null)
{
MethodInfo method = typeof(CSMInstanceFactory).GetMethod("CreateInstance");
method = method.MakeGenericMethod(type);
return method.CreateDelegate(typeof(CreateInstance)) as CreateInstance;
}
return CilCreateInstanceByType(type, ctor);
}
private static CreateInstance CilCreateInstanceByType(Type type, ConstructorInfo ctor)
{
string constructor = type.Name + ".Ctor";
Type[] parametertypes = new Type[0];
DynamicMethod method = new DynamicMethod(constructor, type, parametertypes, typeof(Activator));
ILGenerator generator = method.GetILGenerator(2);
generator.Emit(OpCodes.Newobj, ctor);
generator.Emit(OpCodes.Ret);
return method.CreateDelegate(typeof(CreateInstance)) as CreateInstance;
}
public static object CreateInstanceArrayByType(Type type, int amount)
{
MethodInfo method = typeof(CSMInstanceFactory).GetMethod("CreateInstanceArray");
MethodInfo genericMethod = method.MakeGenericMethod(type);
return genericMethod.Invoke(null, new object[] { amount });
}
And below the code I commented out which resulted in it working.
internal static CreateInstance CreateInstanceByType(Type type)
{
//check constructor
ConstructorInfo ctor = null;
//ConstructorInfo[] ctors =
// type.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
//for (int i = 0; i < ctors.Length; i++)
//{
// if (ctors[i].GetParameters().Length == 0)
// {
// ctor = ctors[i];
// break;
// }
//}
if (ctor == null)
{
//MethodInfo method = typeof(CSMInstanceFactory).GetMethod("CreateInstance");
//method = method.MakeGenericMethod(type);
//return method.CreateDelegate(typeof(CreateInstance)) as CreateInstance;
}
//return CilCreateInstanceByType(type, ctor);
return null;
}
Aucun commentaire:
Enregistrer un commentaire