【问题标题】:Using System.Reflection.Emit.ILGenerator to call Random in VB.Net?使用 System.Reflection.Emit.ILGenerator 在 VB.Net 中调用 Random?
【发布时间】:2011-09-13 04:08:37
【问题描述】:

我正在用我自己的语言为 .Net 可执行文件生成输出...从我的语言翻译的操作码(称为“随机”)应该在特定范围内创建一个随机数。

我的代码的目标是使用 System.Reflection.Emit.ILGenerator 类生成随机数...为了了解 CIL 代码的外观,我创建了一些 vb.net 代码:

Sub Main()
    Dim A As Random

    A = New Random

    Console.WriteLine(A.Next(100))
End Sub

ILDASM 报告为:

.method public static void  Main() cil managed
{
  .entrypoint
  .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       23 (0x17)
  .maxstack  2
  .locals init ([0] class [mscorlib]System.Random A)
  IL_0000:  nop
  IL_0001:  newobj     instance void [mscorlib]System.Random::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ldc.i4.s   100
  IL_000a:  callvirt   instance int32 [mscorlib]System.Random::Next(int32)
  IL_000f:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0014:  nop
  IL_0015:  nop
  IL_0016:  ret
} // end of method Main::Main

我可以使用 ILGenerator.Emit 方法重现所有内容;除了行 IL_0001 ("newobj instance void [mscorlib]System.Random::.ctor()")...

希望我没有用太多信息让任何人不知所措。但我认为在描述一个对我来说似乎很复杂的问题时,最好是冗长。

我终于有了到目前为止我已经生成的代码:

 Sub EmitRandom()
    Dim NewRandom As New Random
    Dim stringtype As Type = GetType(System.Random)

    Dim paramtypes() As Type = {GetType(Integer)}, blankparams() As Type = {}
    'Dim RandomMethod = stringtype.GetMethod("New", paramtypes)

    m_ILGen.Emit(OpCodes.Newobj, New Random().GetType)

    EmitStoreInLocal(tempVariableRnd)
    EmitLoadLocal(tempVariableRnd)

    m_ILGen.Emit(OpCodes.Callvirt, stringtype.GetMethod("Next", paramtypes))
End Sub

发出以下代码:

.
.
.
IL_0073:  newobj     [mscorlib]System.Random
IL_0078:  stloc.2
IL_0079:  ldloc.2
IL_007a:  callvirt   instance int32 [mscorlib]System.Random::Next(int32)
.
.
.

我已经尝试过的事情

  • 想出一种方法来指向 IL_Gen.Emit(OpCodes.NewObj, ... ctor())... 不知道怎么做。

  • 想出一种指向 New() 的方法 - 因为这似乎就是 .ctor() 的含义... New 只能用作初始化程序。

    李>
  • 只是禁用 Random 功能,直到我想出更好的发射方式。

这个问题对我来说似乎很难,但我知道有人比我更容易理解代码生成和 MSIL,并且愿意指出答案。

感谢您的宝贵时间,

多米尼克

【问题讨论】:

  • 请记住,如果您每次都创建一个新的 Random,您将获得糟糕的性能和低随机性。

标签: cil reflection.emit ilgenerator


【解决方案1】:

你需要使用ConstructorInfo:

 m_ILGen.Emit(OpCodes.Newobj, GetType(Random).GetConstructor(Type.EmptyTypes))

另外 - 从本地存储和加载是不必要的。您真的只想要等效于 new Random().Next(100),对吗?...在​​这种情况下,从本地存储和加载永远不会发生。

【讨论】:

  • 一行代码改变了我的一天。谢谢 JennN825。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
  • 2016-04-26
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多