Hi again, I'm trying to instantiate a new object. For that I'm using
something like:
var asm = AssemblyFactory.GetAssembly(this.GetType().Assembly.Location);
// for some typedefinitions in that assembly, for all its methods:
var objectRef = asm.MainModule.TypeReferences.Add(typeof(object));
var ins = il.Create(OpCodes.Newobj, objectRef);
I'm getting the following exception:
TestCase 'Moq.Tests.Instrumentation.InstrumentationFixture.InstrumentsClass'
failed: System.ArgumentException : opcode
at Mono.Cecil.Cil.CilWorker.Create(OpCode opcode, TypeReference type)
The TypeReferences.Add(Type type) extension method (and an accompanying
AssemblyReferences.Add(Assembly assembly)) are defined as follows:
/// <summary>
/// Mono Cecil API extensions.
/// </summary>
public static class AssemblyReferenceCollectionExtensions
{
/// <summary>
/// Adds a reference to the given assembly if one does not exist already in
the collection.
/// </summary>
/// <param name="collection">The collection to add the reference to.</param>
/// <param name="assembly">The reflection assembly to add as a reference to
the collection.</param>
/// <returns>The <see cref="AssemblyNameReference"/> that was newly added or
located (if already existing).</returns>
public static AssemblyNameReference Add(this AssemblyNameReferenceCollection
collection, Assembly assembly)
{
var asmName = assembly.GetName();
var asmRef = collection.Cast<AssemblyNameReference>()
.Where(r => r.FullName == asmName.FullName)
.FirstOrDefault();
if (asmRef == null)
{
asmRef = new AssemblyNameReference(
asmName.Name, asmName.CultureInfo.Name, asmName.Version);
asmRef.PublicKeyToken = asmName.GetPublicKeyToken();
asmRef.HashAlgorithm = (AssemblyHashAlgorithm)asmName.HashAlgorithm;
asmRef.Culture = asmName.CultureInfo.ToString();
collection.Add(asmRef);
}
return asmRef;
}
}
/// <summary>
/// Mono Cecil API extensions.
/// </summary>
public static class TypeReferenceCollectionExtensions
{
/// <summary>
/// Adds the given type as a reference and returns the corresponding
/// <see cref="TypeReference"/>.
/// </summary>
public static TypeReference Add(this TypeReferenceCollection collection,
Type type)
{
var asmRef = collection.Container.AssemblyReferences.Add(type.Assembly);
var typeRef = new TypeReference(type.Name, type.Namespace, asmRef,
type.IsValueType);
collection.Container.TypeReferences.Add(typeRef);
return typeRef;
}
}
Is there anything obviously wrong with the way I'm constructing the assembly
reference and type reference to the imported type? Is the type reference
scope == to the imported assembly reference? or should it be the destination
assembly definition?
thanks in advance!
--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1
425.329.3471
--~--~---------~--~----~------------~-------~--~----~
--
mono-cecil
-~----------~----~----~----~------~----~------~--~---