Hi,
I'm currently using cecil to instrument our application. I've
stumbeled into a little problem. Maybe I'm doing something wrong but I
have the following scenario:
MethodReference mr = module.Import(a_method_definition);
if e.g. a parameter or return value is of nested type:
Kalle.InnerKalle
class Kalle
{
class InnerKalle
{
}
}
it will have the correct reference of InnerKalle (TypeReference)
though the {InnerKalle}.DeclaringType is null instead of TypeReference
Kalle. This problem occurs when I need to clone a method and add it to
a another assembly than the original method, and then imports the
method def as method ref to add it as Override.
What I do is basically the following (see below code snippet). It
might be totally out of line but the result (using reflector) seems
ok. But shouldn't nested typerefs be resolved directly when importing?
I also wonder if I would add a Clone(TypeDefinition context); would it
end up into the cecil dist (if properly implemented ;-), i.e. it will
detect the scope and thus do correct imports of typerefs if neccesary.
Cheers,
Mario
-------------------------------- CODE SNIPPET
----------------------------------
public static void EnsureParameterReferences(TypeReference
method_target, IMethodSignature methd)
{
foreach (ParameterDefinition prm in methd.Parameters)
{
if (prm.ParameterType.Scope != method_target.Scope)
prm.ParameterType = DeepImportType(prm.ParameterType,
method_target.Module);
}
}
public static void MockupNestedClassesForRefMethod(MethodReference
ref_method,MethodDefinition method_def)
{
ParameterDefinitionCollection prm_ref = ref_method.Parameters;
ParameterDefinitionCollection prm_def = method_def.Parameters;
int cnt = prm_def.Count;
for(int i = 0;i < cnt;i++)
{
if (null != prm_def[i].ParameterType.DeclaringType)
prm_ref[i] = prm_def[i];
}
if (null != method_def.ReturnType.ReturnType.DeclaringType)
ref_method.ReturnType.ReturnType =
method_def.ReturnType.ReturnType;
}
public static TypeReference DeepImportType(TypeReference
type,ModuleDefinition module)
{
TypeReference resolved_ref = module.Import(type);
TypeReference mockup = resolved_ref;
for (TypeReference spanner = type.DeclaringType;
spanner != null;
spanner = spanner.DeclaringType,mockup =
mockup.DeclaringType)
{
mockup.DeclaringType = module.Import(spanner);
}
return resolved_ref;
}
--~--~---------~--~----~------------~-------~--~----~
--
mono-cecil
-~----------~----~----~----~------~----~------~--~---