Trouble with “Assembly.EntryPoint.Invoke” [C#]

不打扰是莪最后的温柔 提交于 2020-01-13 19:30:30

问题


I have the following problem:
I am compiling C#-code at runtime using the CSharpCodeProvider in Microsoft.CSharp. The created application runs perfectly, if I double-click on the generated file.

If, however, I am loading my created assembly with Assembly.Load and invoking the entrypoint-method with Assembly.Load("...").EntryPoint.Invoke(null, null), I get a NullReferenceException.


The NullReferenceException is referring to the value of the .EntryPoint-Property.
When I debug the variable containing the loaded Assembly, VisualStudio shows the following:


Larger image

The error is in German and means The value of "local" or argument "asm" is not available in this instruction pointer and can therefore not be determined. It may have been removed during optimization.


I want to add at this point that my generated assembly is not optimized (I also added the compiler argument /optimize-, which prevents optimization.)
I performed an other test to determine the error source by trying this Code:
Assembly asm = Assembly.LoadFile(Assembly.GetExecutingAssembly().Location);

asm.EntryPoint.Invoke(null, argv);

This code is also throwing a NullReferenceException at the line containing the Invoke-call.


Does someone here know, where this error is coming from and I can solve it?
Thank you very much :)


EDIT:

The entrypoint-method is defined as follows:

namespace tmp
{
   public static class Program
   {
      [STAThread]
      public static void Main(string[] argv)
      { ... }
   }
}

I also tried to invoke it with .EntryPoint.Invoke(null, new string[]{"test", "argument"}), but it didn't solve the problem :/

EDIT #2: I found my error - please look at the comment from @Hans Passant and myself for the soulution

~closed~


回答1:


Copy and paste from Hans Passant's comment:

// Get your assembly.
Assembly asm = Assembly.LoadFile(Assembly.GetExecutingAssembly().Location);

// Get your point of entry.
MethodInfo entryPoint = asm.EntryPoint;

// Invoke point of entry with arguments.
entryPoint.Invoke(null, new object[] { new string[] { "arg1", "arg2", "etc" } } );

If you want to access an assembly from an embedded resource, use this snippet:

byte[] yourResource = Properties.Resources.YourResourceName;

Assembly asm = Assembly.Load(yourResource);



回答2:


what if you try something like this will it work?

Assembly asm = Assembly.LoadFile(Assembly.GetExecutingAssembly().Location);
MethodInfo myMethod = asm.EntryPoint;
myMethod.Invoke(null, args); 

assuming that that you know the method you want to invoke



来源:https://stackoverflow.com/questions/28616405/trouble-with-assembly-entrypoint-invoke-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!