unknown6656
unknown6656

Reputation: 2963

Trouble with "Assembly.EntryPoint.Invoke" [C#]

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:

Error
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~

Upvotes: 3

Views: 7722

Answers (2)

Baccata
Baccata

Reputation: 591

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);

Upvotes: 3

MethodMan
MethodMan

Reputation: 18843

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

Upvotes: 0

Related Questions