动态编译里用的问本代码怎么访问主进程里的模块的里全局变量与自定义函数
可以通过加载函数地址getprocaddress后调用进程中的函数,获得函数和通过函数返回变量就可以访问。有帮助请采纳谢谢!
请注意,以下示例是使用动态编译的一个简单例子:
Private Function CompileCodeRuntime(ByVal codeToExecute As String) As String
Dim sb As StringBuilder = New StringBuilder()
sb.Append("Namespace customNamespace" & vbCrLf)
sb.Append("Class customClass " & vbCrLf)
sb.Append("Public Function Main() As Integer " & vbCrLf)
sb.Append("Return " & codeToExecute & vbCrLf)
sb.Append("End Function " & vbCrLf)
sb.Append("End Class " & vbCrLf)
sb.Append("End Namespace" & vbCrLf)
Dim CompilerParams As CompilerParameters = New CompilerParameters()
CompilerParams.GenerateInMemory = True
CompilerParams.TreatWarningsAsErrors = False
CompilerParams.GenerateExecutable = False
CompilerParams.CompilerOptions = "/optimize"
' You can add other dlls needed in the 'references'.
Dim references As String() = {"System.dll"}
CompilerParams.ReferencedAssemblies.AddRange(references)
Dim provider As VBCodeProvider = New VBCodeProvider()
Dim compile As CompilerResults = provider.CompileAssemblyFromSource(CompilerParams, sb.ToString())
If compile.Errors.HasErrors Then
Dim text As String = "Compile error: "
For Each ce As CompilerError In compile.Errors
text += "rn" & ce.ToString()
Next
Throw New Exception(text)
End If
Dim Instance = compile.CompiledAssembly.CreateInstance("customNamespace.customClass")
Dim type = Instance.GetType
Dim methodInfo = type.GetMethod("Main")
Return methodInfo.Invoke(Instance, Nothing).ToString()
End Function
在该示例中,定义了一个返回 Integer 值的main方法,而如何计算对应的值完全取决于传入的外部的String,比如传入 2 * (2+3) - 1,那代码就相当于:
Return 2 * (2 + 3) - 1
希望该示例对你有帮助。