本文整理汇总了C#中System.Reflection.Emit.AssemblyBuilder.Save方法的典型用法代码示例。如果您正苦于以下问题:C# AssemblyBuilder.Save方法的具体用法?C# AssemblyBuilder.Save怎么用?C# AssemblyBuilder.Save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Reflection.Emit.AssemblyBuilder
的用法示例。
在下文中一共展示了AssemblyBuilder.Save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SaveAssembly
private static void SaveAssembly(string fullPath, AssemblyBuilder assemblyBuilder)
{
// assemblyBuilder.Save doesn't want to save with full path, so saving to current directory and then
// moving file to final, weird
string fileName = Path.GetFileName(fullPath);
if (File.Exists(fileName))
{
File.Delete(fullPath);
}
assemblyBuilder.Save(fileName);
if (fileName != fullPath)
{
string targetDirectory = Path.GetDirectoryName(fullPath);
Debug.Assert(targetDirectory != null, "targetDirectory != null");
Directory.CreateDirectory(targetDirectory);
Debug.Assert(fileName != null, "fileName != null");
if (!File.Exists(fullPath))
{
File.Move(fileName, fullPath);
}
}
}
示例2: Save
void Save(AssemblyBuilder builder, string filename)
{
switch (Parameters.Platform)
{
case "x86":
builder.Save(filename, PortableExecutableKinds.Required32Bit, ImageFileMachine.I386);
break;
case "x64":
builder.Save(filename, PortableExecutableKinds.PE32Plus, ImageFileMachine.AMD64);
break;
case "itanium":
builder.Save(filename, PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64);
break;
default: //AnyCPU
builder.Save(filename);
break;
}
}
示例3: CodeGen
public CodeGen(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));
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
//(
// mainProgram.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes),
// new List<FunctionDefinition.Argument>()
//);
SymbolTable symbolTable = new SymbolTable(modb.DefineType("__Program"));
symbolTable.AddFunctionHeader("__Main", MethodAttributes.Static, null, new FunctionDefinition.Argument[]{});
//symbolTable.functionTable.AddHeader("Main", mainProgramDef);
stmt = PreGenerate(stmt, symbolTable);
stmt = ImportList(stmt, symbolTable);
// CodeGenerator
var il = symbolTable.functionTable["__Main"].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(symbolTable.functionTable["__Main"].methodDefinition);
symbolTable.typeTable.types[0].typeBuilder.CreateType();
asmb.Save(moduleName);
foreach (var symbol in symbolTable.Locals)
{
Console.WriteLine("{0}: {1}", symbol.Key, symbol.Value);
}
symbolTable = null;
il = null;
}
示例4: CodegenUnit
internal CodegenUnit(AssemblyName asmName)
{
var fileName = asmName.Name + ".dll";
var pdbName = asmName + ".pdb";
// so that we can run multiple tests at once and not lose the info
if (UnitTest.CurrentTest != null)
{
fileName = asmName + ", " + UnitTest.PersistentId + ".dll";
pdbName = asmName + ".pdb";
}
#if TRACE
try
{
_asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
_mod = _asm.DefineDynamicModule(fileName, true);
// Mark generated code as debuggable.
// See http://blogs.msdn.com/jmstall/archive/2005/02/03/366429.aspx for explanation.
var daCtor = typeof(DebuggableAttribute).GetConstructor(new []{typeof(DebuggableAttribute.DebuggingModes)});
var daBuilder = new CustomAttributeBuilder(daCtor, new object[] {
DebuggableAttribute.DebuggingModes.DisableOptimizations |
DebuggableAttribute.DebuggingModes.Default });
_asm.SetCustomAttribute(daBuilder);
// Mark generated code as non-user code.
// See http://stackoverflow.com/questions/1423733/how-to-tell-if-a-net-assembly-is-dynamic for explanation.
var cgCtor = typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes);
var cgBuilder = new CustomAttributeBuilder(cgCtor, new object []{});
_asm.SetCustomAttribute(cgBuilder);
var hasAlreadyBeenDumped = false;
Action dumpAssembly = () =>
{
if (!hasAlreadyBeenDumped && _asm != null)
{
try
{
// todo. before dumping make sure that all types are completed or else the dump will simply crash
// this is a complex task, but it needs to be resolved for generic case
_asm.Save(fileName);
}
catch (Exception ex)
{
var trace = String.Format("Codegen unit '{0}' has failed to dump the asm:{1}{2}",
asmName.FullName, Environment.NewLine, ex);
Log.WriteLine(trace);
SafetyTools.SafeDo(() =>
{
File.WriteAllText(fileName, trace);
File.Delete(pdbName);
});
}
finally
{
hasAlreadyBeenDumped = true;
}
}
};
_dumpAssembly = dumpAssembly;
// do not use DomainUnload here because it never gets fired for default domain
// however, we need not to neglect because R#'s unit-test runner never exits process
AppDomain.CurrentDomain.DomainUnload += (o, e) => dumpAssembly();
AppDomain.CurrentDomain.ProcessExit += (o, e) => dumpAssembly();
AppDomain.CurrentDomain.UnhandledException += (o, e) => dumpAssembly();
}
catch (Exception ex)
{
var trace = String.Format("Codegen unit '{0}' has failed to initialize:{1}{2}",
asmName.FullName, Environment.NewLine, ex);
Log.WriteLine(trace);
SafetyTools.SafeDo(() =>
{
File.WriteAllText(fileName, trace);
File.Delete(pdbName);
});
throw;
}
#else
_asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
_asm.SetCustomAttribute(new CustomAttributeBuilder(typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes), new object[] { }));
_mod = _asm.DefineDynamicModule(fileName, false);
#endif
}
示例5: WriteWrapperToDisk
/*
* Method: WriteWrapperToDisk
*
* Writes the generated wrapper out to disk. Should only be called for permanent wrappers.
*/
private void WriteWrapperToDisk(AssemblyBuilder assemblyBuilder, string wrapperPath)
{
try
{
FileInfo wrapperFile = new FileInfo(wrapperPath);
if (wrapperFile.Exists)
{
wrapperFile.Delete();
}
switch (_targetProcessorArchitecture)
{
case UtilitiesProcessorArchitecture.X86:
assemblyBuilder.Save
(
wrapperFile.Name,
PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit,
ImageFileMachine.I386
);
break;
case UtilitiesProcessorArchitecture.AMD64:
assemblyBuilder.Save
(
wrapperFile.Name,
PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus,
ImageFileMachine.AMD64
);
break;
case UtilitiesProcessorArchitecture.IA64:
assemblyBuilder.Save
(
wrapperFile.Name,
PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus,
ImageFileMachine.IA64
);
break;
case UtilitiesProcessorArchitecture.ARM:
assemblyBuilder.Save
(
wrapperFile.Name,
PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit,
ImageFileMachine.ARM
);
break;
case UtilitiesProcessorArchitecture.MSIL:
default:
// If no target processor architecture was passed, we assume MSIL; calling Save
// with no parameters should be equivalent to saving as ILOnly.
assemblyBuilder.Save(wrapperFile.Name);
break;
}
// AssemblyBuilder doesn't always throw when it's supposed to write stuff to a non-writable
// network path. Make sure that the assembly actually got written to where we wanted it to.
File.GetLastWriteTime(wrapperPath);
}
catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception.
{
if (ExceptionHandling.NotExpectedException(e))
throw;
if (!Silent)
{
Log.LogWarningWithCodeFromResources("ResolveComReference.ErrorCreatingWrapperAssembly", ItemName, e.Message);
}
throw new ComReferenceResolutionException(e);
}
}
示例6: DefineVersionInfoResource
[Test] // DefineVersionInfoResource (String, String, String, String, String)
public void TestDefineVersionInfoResource2_Culture_NotSupported ()
{
AssemblyName aname = new AssemblyName ();
aname.CultureInfo = new CultureInfo ("nl-BE");
aname.Name = "lib";
aname.Version = new Version (3, 5, 7);
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
aname, AssemblyBuilderAccess.RunAndSave,
tempDir);
// AssemblyCulture
Type attrType = typeof (AssemblyCultureAttribute);
ConstructorInfo ci = attrType.GetConstructor (new Type [] { typeof (String) });
CustomAttributeBuilder cab = new CustomAttributeBuilder (
ci, new object [1] { "doesnotexist" });
ab.SetCustomAttribute (cab);
ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E");
try {
ab.Save ("lib.dll");
Assert.Fail ("#A1");
} catch (CultureNotFoundException ex) {
}
ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname,
AssemblyBuilderAccess.RunAndSave, tempDir);
// AssemblyCulture
attrType = typeof (AssemblyCultureAttribute);
ci = attrType.GetConstructor (new Type [] { typeof (String) });
cab = new CustomAttributeBuilder (ci, new object [1] { "neutral" });
ab.SetCustomAttribute (cab);
ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E");
try {
ab.Save ("lib.dll");
Assert.Fail ("#B1");
} catch (CultureNotFoundException ex) {
}
}
示例7: Save
public void Save(AssemblyBuilder assemblyBuilder)
{
#if DEBUG_PROXY_OUTPUT
assemblyBuilder.Save("generatedAssembly.dll");
#endif
}
示例8: ManifestModule
public void ManifestModule ()
{
AssemblyName aname = new AssemblyName ("ManifestModule1");
ab = domain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.RunAndSave,
tempDir);
Assert.IsNotNull (ab.ManifestModule, "#A1");
Assert.AreEqual (1, ab.GetModules ().Length, "#A2");
Assert.AreEqual (typeof (ModuleBuilder), ab.ManifestModule.GetType (), "#A3");
ModuleBuilder mb1 = (ModuleBuilder) ab.ManifestModule;
Assert.AreSame (mb1, ab.GetModules () [0], "#B1");
Assert.IsFalse (mb1.IsResource (), "#B2");
Assert.AreSame (mb1, ab.ManifestModule, "#B3");
ab.Save ("ManifestModule.dll");
ModuleBuilder mb2 = (ModuleBuilder) ab.ManifestModule;
Assert.AreSame (mb2, ab.GetModules () [0], "#C1");
Assert.IsFalse (mb2.IsResource (), "#C2");
Assert.AreSame (mb2, ab.ManifestModule, "#C3");
Assert.AreSame (mb1, mb2, "#C4");
}
示例9: SetCustomAttribute
[Test] // SetCustomAttribute (CustomAttributeBuilder)
public void TestSetCustomAttribute1 ()
{
Assembly a;
AssemblyName an;
AssemblyName check;
Attribute attr;
string filename;
an = new AssemblyName ();
an.Name = "TestSetCustomAttributeA";
ab = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, tempDir);
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyVersionAttribute).
GetConstructor (new Type [] { typeof (string) }), new object [] { "1.2.3.4"}));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyCultureAttribute).
GetConstructor (new Type [] { typeof (string) }), new object [] { "bar"}));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyAlgorithmIdAttribute).
GetConstructor (new Type [] { typeof (AssemblyHashAlgorithm) }),
new object [] { AssemblyHashAlgorithm.MD5 }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyFlagsAttribute).
GetConstructor (new Type [] { typeof (uint) }), new object [] { (uint)0xff }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyDelaySignAttribute).
GetConstructor (new Type [] { typeof (bool) }), new object [] { true }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (FooAttribute).
GetConstructor (Type.EmptyTypes), new object [0]));
ab.Save ("TestSetCustomAttributeA.dll");
filename = Path.Combine (tempDir, "TestSetCustomAttributeA.dll");
check = AssemblyName.GetAssemblyName (filename);
Assert.AreEqual (CultureInfo.InvariantCulture, check.CultureInfo, "#A1");
#if NET_2_0
Assert.AreEqual (AssemblyNameFlags.None, check.Flags, "#A2");
#else
Assert.AreEqual (AssemblyNameFlags.PublicKey, check.Flags, "#A2");
#endif
Assert.AreEqual ("TestSetCustomAttributeA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", check.FullName, "#A3");
#if NET_2_0
Assert.IsNull (check.GetPublicKey (), "#A4");
#else
Assert.AreEqual (new byte [0], check.GetPublicKey (), "#A4");
#endif
#if NET_2_0
Assert.AreEqual (new byte [0], check.GetPublicKeyToken (), "#A5");
#else
Assert.IsNull (check.GetPublicKeyToken (), "#A5");
#endif
Assert.AreEqual (AssemblyHashAlgorithm.SHA1, check.HashAlgorithm, "#A6");
Assert.IsNull (check.KeyPair, "#A7");
Assert.AreEqual ("TestSetCustomAttributeA", check.Name, "#A8");
#if NET_2_0
//Assert.AreEqual (ProcessorArchitecture.MSIL, check.ProcessorArchitecture, "#A9");
#endif
Assert.AreEqual (new Version (0, 0, 0, 0), check.Version, "#A10");
Assert.AreEqual (AssemblyVersionCompatibility.SameMachine, check.VersionCompatibility, "#A11");
using (FileStream fs = File.OpenRead (filename)) {
byte [] buffer = new byte [fs.Length];
fs.Read (buffer, 0, buffer.Length);
a = Assembly.Load (buffer);
}
attr = Attribute.GetCustomAttribute (a, typeof (AssemblyVersionAttribute));
Assert.IsNotNull (attr, "#A12a");
Assert.AreEqual ("1.2.3.4", ((AssemblyVersionAttribute) attr).Version, "#A12b");
attr = Attribute.GetCustomAttribute (a, typeof (AssemblyCultureAttribute));
Assert.IsNotNull (attr, "#A13a");
Assert.AreEqual ("bar", ((AssemblyCultureAttribute) attr).Culture, "#A13b");
attr = Attribute.GetCustomAttribute (a, typeof (AssemblyAlgorithmIdAttribute));
Assert.IsNotNull (attr, "#A14a");
Assert.AreEqual ((uint) AssemblyHashAlgorithm.MD5, ((AssemblyAlgorithmIdAttribute) attr).AlgorithmId, "#A14b");
attr = Attribute.GetCustomAttribute (a, typeof (AssemblyFlagsAttribute));
Assert.IsNotNull (attr, "#A15a");
Assert.AreEqual ((uint) 0xff, ((AssemblyFlagsAttribute) attr).Flags, "#A15b");
attr = Attribute.GetCustomAttribute (a, typeof (FooAttribute));
Assert.IsNotNull (attr, "#A16");
an = new AssemblyName ();
an.CultureInfo = new CultureInfo ("nl-BE");
an.Flags = AssemblyNameFlags.Retargetable;
an.Name = "TestSetCustomAttributeB";
#if NET_2_0
an.ProcessorArchitecture = ProcessorArchitecture.IA64;
#endif
an.Version = new Version (1, 3, 5, 7);
an.VersionCompatibility = AssemblyVersionCompatibility.SameDomain;
ab = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, tempDir);
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyVersionAttribute).
GetConstructor (new Type [] { typeof (string) }), new object [] { "1.2.3.4" }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyCultureAttribute).
GetConstructor (new Type [] { typeof (string) }), new object [] { "en-US" }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyAlgorithmIdAttribute).
GetConstructor (new Type [] { typeof (AssemblyHashAlgorithm) }),
new object [] { AssemblyHashAlgorithm.MD5 }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyFlagsAttribute).
GetConstructor (new Type [] { typeof (uint) }), new object [] { (uint) 0x0100 }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyDelaySignAttribute).
GetConstructor (new Type [] { typeof (bool) }), new object [] { true }));
ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (FooAttribute).
//.........这里部分代码省略.........
示例10: SaveAssembly
public static void SaveAssembly(AssemblyBuilder assemblyBuilder)
{
assemblyBuilder.Save(AssemblyFileName);
}
示例11: Save
private static void Save(AssemblyBuilder assembly, ProxyContext context)
{
if ((context.Access & AssemblyBuilderAccess.Save) == AssemblyBuilderAccess.Save)
{
assembly.Save(assembly.GetName().Name + ".dll");
if (context.Verify)
{
AssemblyVerification.Verify(assembly);
}
}
}
示例12: SaveAssemblyBuilder
private string SaveAssemblyBuilder(System.Runtime.InteropServices.ComTypes.ITypeLib typeLib, AssemblyBuilder asmBldr, string rcwName)
{
string assem = null;
FileInfo info = new FileInfo(rcwName);
string name = info.Name;
if (info.Exists)
{
if (!this.options.overwriteRCW)
{
goto Label_00D2;
}
if ((this.typeLibName != null) && string.Equals(this.typeLibName, info.FullName, StringComparison.OrdinalIgnoreCase))
{
throw new Exception(System.Design.SR.GetString("AXCannotOverwriteFile", new object[] { info.FullName }));
}
if ((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
throw new Exception(System.Design.SR.GetString("AXReadOnlyFile", new object[] { info.FullName }));
}
try
{
info.Delete();
asmBldr.Save(name);
goto Label_00D2;
}
catch (Exception)
{
throw new Exception(System.Design.SR.GetString("AXCannotOverwriteFile", new object[] { info.FullName }));
}
}
asmBldr.Save(name);
Label_00D2:
assem = info.FullName;
this.AddReferencedAssembly(assem);
this.AddTypeLibAttr(typeLib);
this.AddGeneratedAssembly(assem);
return assem;
}
示例13: GenerateExe
public void GenerateExe()
{
string AssemblyName = "TestAssembly";
string ClassName = "TestClass";
string ExeName = ClassName + ".exe";
// 获得应用程序域,用于创建程序集。
domain = Thread.GetDomain();
// 创建程序集名称。
name = new AssemblyName();
name.Name = AssemblyName;
// 创建程序集。
asmbuilder = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
// 创建模块。
modbuilder = asmbuilder.DefineDynamicModule(ExeName);
// 创建类型。
typbuilder = modbuilder.DefineType(ClassName);
// 创建全局变量(类的静态变量)
fld = typbuilder.DefineField("haha", typeof(int), FieldAttributes.Static);
// 创建静态方法Add:public static int Add(int,int)
addBuilder = typbuilder.DefineMethod("Add", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
// 创建静态方法Add:public static int Fact(int)
factBuilder = typbuilder.DefineMethod("Fact", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int) });
// 创建静态方法Main:public static void Main(string[])
mainBuilder = typbuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { typeof(string[]) });
// Add方法的代码生成器
iladd = addBuilder.GetILGenerator();
// 产生Add方法的代码
GenerateCodeForAdd();
// Fact方法的代码生成器
ilfact = factBuilder.GetILGenerator();
// 产生Fact方法的代码
GenerateCodeForFact();
// Main方法的代码生成器
ilmain = mainBuilder.GetILGenerator();
// 产生Main方法的代码。
GenerateCodeForMain();
// 类里所有东西都已经定义好了,现在要创建这个类。
typbuilder.CreateType();
// 设置入口点。
asmbuilder.SetEntryPoint((modbuilder.GetType(ClassName)).GetMethod("Main"));
// 保存到EXE文件。
asmbuilder.Save(ExeName);
}
示例14: CreateRTAssemblyAndModule
/// <summary>
/// Internal Assmebly runtime creation
/// </summary>
private void CreateRTAssemblyAndModule()
{
AssemblyName assemblyName = new AssemblyName(this.XmlAssemblyData.FileName);
Version outVersion;
if (Version.TryParse(this.XmlAssemblyData.Version, out outVersion) == false)
throw new InvalidDataException("unable to parse the Assembly Version data");
assemblyName.Version = outVersion;
RTAssemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
// For a single-module assembly, the module name is usually
// the assembly name plus an extension.
ModuleBuilder moduleBuilder = RTAssemblyBuilder.DefineDynamicModule(this.XmlAssemblyData.FileName + ".dll");
// foreach namespace create type
foreach(XmlModelNamespaceRoot xmlNamespace in this.XmlAssemblyData.Namespaces)
{
CreateRTNamespaceType(moduleBuilder, xmlNamespace);
}
RTAssemblyBuilder.Save(this.XmlAssemblyData.FileName + ".dll");
}
示例15: SaveAssembly
private void SaveAssembly(
string fullyQualifiedModuleName,
AssemblyBuilder assemblyBuilder,
TypeBuilder typeBuilder)
{
Type NireType = typeBuilder.CreateType();
NireType.GetMethod("Main").Invoke(null, new string[] {null});
// set the entry point for the application and save it
assemblyBuilder.SetEntryPoint(this.methodbuilder, PEFileKinds.ConsoleApplication);
assemblyBuilder.Save(fullyQualifiedModuleName);
}