dew*_*ice 2 c# memory exception
这是我从内存中运行一个简单的自制.Net可执行文件的工作代码:
FileStream fs = new FileStream(@"simple.exe",FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
fs.Close();
br.Close();
Assembly a = Assembly.Load(bin);
MethodInfo method = a.EntryPoint;
if (method == null) return;
object o = a.CreateInstance(method.Name);
method.Invoke(o, null);
Run Code Online (Sandbox Code Playgroud)
但是这段代码只适用于微小的.exe文件而不是其他可执行文件,如putty或其他更大的.net文件.
当我想使用另一个exe时,它说:
mscorlib.dll中发生未处理的"System.Reflection.TargetParameterCountException"类型异常
附加信息:参数计数不匹配.
对于这一行: method.Invoke(o, /*here*/ null);
问题:我能做什么,我应该寻找什么?请原谅我在c#中的内存处理方面没什么了不起的.我想从内存中为编程工具项目运行更大的exe文件
注意:我的工作示例是一个简单的c#代码,用于在控制台上打印字符串.
更新:感谢Marc的回答,这是最终的代码:
FileStream fs = new FileStream(@"EverySample.exe", FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
fs.Close();
br.Close();
Assembly a = Assembly.Load(bin);
MethodInfo method = a.EntryPoint;
if (method == null) return;
object[] parameters = method.GetParameters().Length == 0 ? null : new object[] { new string[0] };
method.Invoke(null, parameters);
Run Code Online (Sandbox Code Playgroud)
切入点是Main()方法或等同物.这有多个签名; 你可以有一个无参数Main(),但你也可以Main(string[]).所以:你应该检查method(GetParameters())上的参数,并传入一些东西 - 大概是空的string[].
请注意,入口点通常是static; 没有必要传入o,并且您现有的CreateInstance代码是非敏感的(它将方法名称传递给需要类型名称的东西).您可以将其null作为第一个参数传递.