本文整理汇总了C#中System.Reflection.Emit.TypeBuilder.CreateType方法的典型用法代码示例。如果您正苦于以下问题:C# TypeBuilder.CreateType方法的具体用法?C# TypeBuilder.CreateType怎么用?C# TypeBuilder.CreateType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Reflection.Emit.TypeBuilder
的用法示例。
在下文中一共展示了TypeBuilder.CreateType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateType
/// <summary>
/// Generates the type.
/// </summary>
/// <returns></returns>
public Type GenerateType()
{
if (_generatedType == null)
{
// Setup the assembly and type builder
AssemblyName assemblyName = new AssemblyName("Mock.Generated-" + _interfaceToImplement.Name);
AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
_typeBuilder = moduleBuilder.DefineType("Mock.Generated.Mock" + _interfaceToImplement.Name, TypeAttributes.Public);
_typeBuilder.AddInterfaceImplementation(_interfaceToImplement);
// Generate the body of the type
this.CreateFields();
this.CreateConstructor();
foreach (MethodInfo method in _interfaceToImplement.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(m => !m.Name.StartsWith("get_")))
{
this.ImplementMethod(method);
}
foreach (PropertyInfo property in _interfaceToImplement.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
this.ImplementProperty(property);
}
// Store the generated type for use again
_generatedType = _typeBuilder.CreateType();
}
return _generatedType;
}
示例2: CreateType
public Type CreateType(TypeBuilder typeBuilder)
{
Type proxyType = typeBuilder.CreateType();
((AssemblyBuilder)typeBuilder.Assembly).Save("ProxyAssembly.dll");
AssemblyAssert.IsValidAssembly("ProxyAssembly.dll");
return proxyType;
}
示例3: Compile
public IAlgorithm Compile(InstructionInfo[] Instructions)
{
lock (GlobalLock)
{
Stopwatch sw = Stopwatch.StartNew();
typeBuilder = modBuilder.DefineType("AlgoClass_" + CompiledClasses, TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout,
typeof(object),
new Type[] { typeof(IAlgorithm) });
CreateConstructor(typeBuilder);
CreateDeconstructor(typeBuilder);
CreateUlongMethod(typeBuilder, Instructions);
//CreateByteMethod(typeBuilder);
Type InitType = typeBuilder.CreateType();
Algorithm = (IAlgorithm)InitType.GetConstructor(new Type[] { }).Invoke(new object[] { });
//asmBuilder.Save("Dderp.dll");
//ulong test = Algorithm.CalculateULong(1);
CompiledClasses++;
sw.Stop();
return Algorithm;
}
}
示例4: Program
public void Program()
{
var tempName = "EvilProg-" + Guid.NewGuid().ToString();
AssemblyName aName = new AssemblyName(tempName);
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save);
programModule = ab.DefineDynamicModule(aName.Name, tempName + ".exe", true);
programType = programModule.DefineType("Program", TypeAttributes.Public);
createReadInInt();
this.program();
var main = functionMap["main"];
programModule.SetUserEntryPoint(main);
ab.SetEntryPoint(main);
programType.CreateType();
string tempPath = tempName + ".exe";
ab.Save(tempPath);
if (File.Exists(Options.ClrExec.Value))
File.Delete(Options.ClrExec.Value);
File.Move(tempPath, Options.ClrExec.Value);
File.Delete(tempPath);
}
示例5: GetTypeNET45
// .NET 4.5 and later have the documented SetMethodBody() method.
static Type GetTypeNET45(TypeBuilder tb, MethodBuilder mb, IntPtr address) {
byte[] code = new byte[1] { 0x2A };
int maxStack = 8;
byte[] locals = GetLocalSignature(address);
setMethodBodyMethodInfo.Invoke(mb, new object[5] { code, maxStack, locals, null, null });
var createdMethod = tb.CreateType().GetMethod(METHOD_NAME, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
return createdMethod.GetMethodBody().LocalVariables[0].LocalType;
}
示例6: CreateType
public Type CreateType(String typeName, Type parent)
{
_typeBuilder = _moduleBuilder.DefineType(typeName,
TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass |
TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout,
parent, new[] { typeof(IProxy) });
_typeBuilder.AddInterfaceImplementation(typeof(IProxy));
ImplementProxyInterface(parent);
var propHandlerDic = OverrideProperties(parent);
GenerateConstructor(propHandlerDic);
return _typeBuilder.CreateType();
}
示例7: CodeGenOld
public CodeGenOld(ParseTreeNode stmt, string moduleName)
{
if (Path.GetFileName(moduleName) != moduleName)
{
throw new System.Exception("can only output into current directory!");
}
AssemblyName name = new AssemblyName(Path.GetFileNameWithoutExtension(moduleName));
AssemblyBuilder asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save);
ModuleBuilder modb = asmb.DefineDynamicModule(moduleName);
mainProgram = modb.DefineType("Program");
var mainArgs = new List<Tuple<string,Type>>();
var mainProgramDef = new FunctionDefinition()
{
methodDefinition=mainProgram.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes),
arguments=new List<FunctionDefinition.Argument>()
};
functionTable.Add("Main",mainProgramDef);
SymbolTable symbolTable = new SymbolTable();
// CodeGenerator
var il = functionTable["Main"].methodDefinition.GetILGenerator();
// Go Compile!
this.GenStmt(stmt, il, symbolTable);
il.Emit(OpCodes.Ldstr, "Press any key to exit the program...");
il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
il.Emit(OpCodes.Call, typeof(System.Console).GetMethod("ReadKey", new Type[] { }));
il.Emit(OpCodes.Ret);
mainProgram.CreateType();
modb.CreateGlobalFunctions();
asmb.SetEntryPoint(functionTable["Main"].methodDefinition);
asmb.Save(moduleName);
foreach (var symbol in symbolTable.locals)
{
Console.WriteLine("{0}: {1}", symbol.Key, symbol.Value);
}
symbolTable = null;
il = null;
}
示例8: ConvertFromTree
//.........这里部分代码省略.........
cur_type = entry_type;
if (!is_main_namespace)
cur_unit = cnn.namespace_name;
else
cur_unit = entry_cur_unit;
if (iii == cnns.Length - 1 && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && iii == cnns.Length - 1)
entry_ns = cnn;
ConvertTypeHeaders(cnn.types);
}
//Переводим псевдоинстанции generic-типов
foreach (ICommonTypeNode ictn in p.generic_type_instances)
{
ConvertTypeHeaderInSpecialOrder(ictn);
}
Dictionary<ICommonNamespaceNode, TypeBuilder> NamespacesTypes = new Dictionary<ICommonNamespaceNode, TypeBuilder>();
for (int iii = 0; iii < cnns.Length; iii++)
{
bool is_main_namespace = cnns[iii].namespace_name == "" && comp_opt.target != TargetType.Dll || comp_opt.target == TargetType.Dll && cnns[iii].namespace_name == "";
if (!is_main_namespace)
{
//определяем синтетический класс для модуля
cur_type = mb.DefineType(cnns[iii].namespace_name + "." + cnns[iii].namespace_name, TypeAttributes.Public);
types.Add(cur_type);
NamespaceTypesList.Add(cur_type);
NamespacesTypes.Add(cnns[iii], cur_type);
if (cnns[iii].IsMain)
{
TypeBuilder attr_class = mb.DefineType(cnns[iii].namespace_name + "." + "$GlobAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute));
ConstructorInfo attr_ci = attr_class.DefineDefaultConstructor(MethodAttributes.Public);
cur_type.SetCustomAttribute(attr_ci, new byte[4] { 0x01, 0x00, 0x00, 0x00 });
attr_class.CreateType();
}
else
{
TypeBuilder attr_class = mb.DefineType(cnns[iii].namespace_name + "." + "$ClassUnitAttr", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(Attribute));
ConstructorInfo attr_ci = attr_class.DefineDefaultConstructor(MethodAttributes.Public);
cur_type.SetCustomAttribute(attr_ci, new byte[4] { 0x01, 0x00, 0x00, 0x00 });
attr_class.CreateType();
}
}
else
{
NamespacesTypes.Add(cnns[iii], entry_type);
}
}
if (comp_opt.target == TargetType.Dll)
{
for (int iii = 0; iii < cnns.Length; iii++)
{
string tmp = cur_unit;
if (cnns[iii].namespace_name != "")
cur_unit = cnns[iii].namespace_name;
else
cur_unit = entry_cur_unit;
foreach (ITemplateClass tc in cnns[iii].templates)
{
CreateTemplateClass(tc);
}
cur_unit = tmp;
}
for (int iii = 0; iii < cnns.Length; iii++)
示例9: Compile
public Type Compile(Type superType, Type stubType, IPersistentVector interfaces, bool onetimeUse, GenContext context)
{
if (_compiledType != null)
return _compiledType;
string publicTypeName = IsDefType || (_isStatic && Compiler.IsCompiling) ? InternalName : InternalName + "__" + RT.nextID();
_typeBuilder = context.AssemblyGen.DefinePublicType(publicTypeName, superType, true);
context = context.WithNewDynInitHelper().WithTypeBuilder(_typeBuilder);
Var.pushThreadBindings(RT.map(Compiler.CompilerContextVar, context));
try
{
if (interfaces != null)
{
for (int i = 0; i < interfaces.count(); i++)
_typeBuilder.AddInterfaceImplementation((Type)interfaces.nth(i));
}
ObjExpr.MarkAsSerializable(_typeBuilder);
GenInterface.SetCustomAttributes(_typeBuilder, _classMeta);
try
{
if (IsDefType)
{
Compiler.RegisterDuplicateType(_typeBuilder);
Var.pushThreadBindings(RT.map(
Compiler.CompileStubOrigClassVar, stubType
));
//,
//Compiler.COMPILE_STUB_CLASS, _baseType));
}
EmitConstantFieldDefs(_typeBuilder);
EmitKeywordCallsiteDefs(_typeBuilder);
DefineStaticConstructor(_typeBuilder);
if (SupportsMeta)
_metaField = _typeBuilder.DefineField("__meta", typeof(IPersistentMap), FieldAttributes.Public | FieldAttributes.InitOnly);
// If this IsDefType, then it has already emitted the closed-over fields on the base class.
if ( ! IsDefType )
EmitClosedOverFields(_typeBuilder);
EmitProtocolCallsites(_typeBuilder);
_ctorInfo = EmitConstructor(_typeBuilder, superType);
if (_altCtorDrops > 0)
EmitFieldOnlyConstructor(_typeBuilder, superType);
if (SupportsMeta)
{
EmitNonMetaConstructor(_typeBuilder, superType);
EmitMetaFunctions(_typeBuilder);
}
EmitStatics(_typeBuilder);
EmitMethods(_typeBuilder);
//if (KeywordCallsites.count() > 0)
// EmitSwapThunk(_typeBuilder);
_compiledType = _typeBuilder.CreateType();
if (context.DynInitHelper != null)
context.DynInitHelper.FinalizeType();
_ctorInfo = GetConstructorWithArgCount(_compiledType, CtorTypes().Length);
return _compiledType;
}
finally
{
if (IsDefType)
Var.popThreadBindings();
}
}
finally
{
Var.popThreadBindings();
}
}
示例10: EnsureTypeBuilt
private void EnsureTypeBuilt(GenContext context)
{
if (_typeBuilder != null)
return;
_baseTypeBuilder = GenerateFnBaseClass(context);
_baseType = _baseTypeBuilder.CreateType();
GenerateFnClass(context, _baseType);
_fnType = _typeBuilder.CreateType();
}
示例11: BuildMemoryManagementType
static Type BuildMemoryManagementType(TypeBuilder typeBuilder, Type memMgmtType, string dllName)
{
foreach (MethodInfo method in memMgmtType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
ParameterInfo[] paramInfos = method.GetParameters();
Type[] parameterTypes = new Type[paramInfos.Length];
for (int i = 0; i < paramInfos.Length; i++)
{
parameterTypes[i] = paramInfos[i].ParameterType;
}
ParameterInfo returnParamInfo = method.ReturnParameter;
MethodBuilder methodBuilder =
typeBuilder.DefinePInvokeMethod(
method.Name, dllName,
MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
CallingConventions.Standard,
returnParamInfo.ParameterType, parameterTypes,
callingConvention, charset);
methodBuilder.SetImplementationFlags(MethodImplAttributes.PreserveSig);
}
return typeBuilder.CreateType();
}
示例12: ModuleBuilder
internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
this.name = this.scopename = name;
this.fqname = fullyqname;
this.assembly = this.assemblyb = assb;
this.transient = transient;
// to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
guid = Guid.FastNewGuidArray ();
// guid = Guid.NewGuid().ToByteArray ();
table_idx = get_next_table_index (this, 0x00, true);
name_cache = new Hashtable ();
us_string_cache = new Dictionary<string, int> (512);
basic_init (this);
CreateGlobalType ();
if (assb.IsRun) {
TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/
Type type = tb.CreateType ();
set_wrappers_type (this, type);
}
if (emitSymbolInfo) {
#if MOONLIGHT
symbolWriter = new Mono.CompilerServices.SymbolWriter.SymbolWriterImpl (this);
#else
Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
if (asm == null)
throw new TypeLoadException ("The assembly for default symbol writer cannot be loaded");
Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl", true);
symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
#endif
string fileName = fqname;
if (assemblyb.AssemblyDir != null)
fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
symbolWriter.Initialize (IntPtr.Zero, fileName, true);
}
}
示例13: VisitClassDecl
public override AstNode VisitClassDecl(ClassDecl ast)
{
m_currentType = GetClrType(ast.Type) as TypeBuilder;
foreach (var method in ast.Methods)
{
Visit(method);
}
GetClrCtor(ast.Type);
m_currentType.CreateType();
return ast;
}
示例14: CreateType
public Type CreateType()
{
if (m_proxyType == null) {
m_typeBuilder = m_moduleBuilder.DefineType(m_className,
TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout,
typeof(object),
new Type[] {m_interfaceType});
//m_typeBuilder.AddInterfaceImplementation(m_interfaceType);
m_innerFieldBuilder = m_typeBuilder.DefineField("inner", m_innerType, FieldAttributes.Private);
BuildConstructor();
foreach (MethodInfo method in m_interfaceType.GetMethods()) {
BuildMethod(method);
}
foreach (PropertyInfo property in m_interfaceType.GetProperties()) {
BuildProperty(property);
}
foreach (EventInfo eventInfo in m_interfaceType.GetEvents()) {
BuildEvent(eventInfo);
}
foreach (MethodBuilder methodBuilder in _unsupportedMethods.Values)
{
BuildNotSupportedException(methodBuilder);
}
m_proxyType = m_typeBuilder.CreateType();
}
return m_proxyType;
}
示例15: Seal
//.........这里部分代码省略.........
.LoadConstant(0) // int object[] object&
.LoadElement<object>(); // object object&
Sigil.Label next;
var done = tryGetIndexEmit.DefineLabel("done");
foreach (var mem in Members)
{
next = tryGetIndexEmit.DefineLabel("next_" + mem.Key);
var memKey = mem.Key;
var field = fields[memKey];
tryGetIndexEmit
.Duplicate() // object object object&
.LoadConstant(memKey); // string object object object&
tryGetIndexEmit.CallVirtual(strEq); // int object object7&
tryGetIndexEmit.BranchIfFalse(next); // object object&
tryGetIndexEmit
.Pop() // object&
.LoadArgument(0) // this object&
.LoadField(field); // fieldType object&
if (field.FieldType.IsValueType)
{
tryGetIndexEmit.Box(field.FieldType); // fieldType object&
}
tryGetIndexEmit.Branch(done); // fieldType object&
tryGetIndexEmit.MarkLabel(next); // object object&
}
tryGetIndexEmit
.Pop() // object&
.LoadNull(); // null object&
tryGetIndexEmit.MarkLabel(done); // *something* object&
tryGetIndexEmit
.StoreIndirect(typeof(object)) // --empty--
.LoadConstant(1) // int
.Return(); // --empty--
var tryGetIndex = tryGetIndexEmit.CreateMethod();
TypeBuilder.DefineMethodOverride(tryGetIndex, typeof(DynamicObject).GetMethod("TryGetIndex"));
// Implement IEnumerable
var getEnumeratorEmit = Sigil.Emit<Func<IEnumerator>>.BuildMethod(TypeBuilder, "GetEnumerator", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard | CallingConventions.HasThis);
var newStrList = typeof(List<string>).GetConstructor(new[] { typeof(int) });
var newEnumerator = Enumerator.GetConstructor(new[] { typeof(List<string>), typeof(object) });
var add = typeof(List<string>).GetMethod("Add");
getEnumeratorEmit.LoadConstant(Members.Count);
getEnumeratorEmit.NewObject(newStrList);
foreach (var mem in Members)
{
getEnumeratorEmit.Duplicate();
getEnumeratorEmit.LoadConstant(mem.Key);
getEnumeratorEmit.Call(add);
}
getEnumeratorEmit.LoadArgument(0);
getEnumeratorEmit.NewObject(newEnumerator);
getEnumeratorEmit.Return();
var getEnumerator = getEnumeratorEmit.CreateMethod();
TypeBuilder.DefineMethodOverride(getEnumerator, typeof(IEnumerable).GetMethod("GetEnumerator"));
// Define ToString()
var toStringEmit = Sigil.Emit<Func<string>>.BuildMethod(TypeBuilder, "ToString", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard | CallingConventions.HasThis);
var objToString = typeof(object).GetMethod("ToString");
var thunkField = TypeBuilder.DefineField("__ToStringThunk", typeof(Func<object, string>), FieldAttributes.Static | FieldAttributes.Private);
var invoke = typeof(Func<object, string>).GetMethod("Invoke");
toStringEmit
.LoadField(thunkField)
.LoadArgument(0)
.CallVirtual(invoke)
.Return();
var toString = toStringEmit.CreateMethod();
TypeBuilder.DefineMethodOverride(toString, objToString);
PocoType = TypeBuilder.CreateType();
// Set the ToStringCallback
var firstInst = PocoType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
var setThunk = firstInst.GetType().GetField("__ToStringThunk", BindingFlags.NonPublic | BindingFlags.Static);
setThunk.SetValue(firstInst, ToStringFunc);
}