Tags down


ILGenerator emiting call GetHashCode on int

By : KDL
Date : October 17 2020, 06:10 AM
I hope this helps you . GetHashCode() is an instance method, hence you need to call it on a "reference". While you don't need to box an integer, the this parameter you need to push onto the stack is not the integer value itself but a pointer to the integer value.
For this reason, you need a local variable in which you can store the integer value, then push a pointer to that local value onto the stack (ldloca.s) and call the instance method:
code :
static void Main(string[] args)
    var method = new DynamicMethod("Get17HashCode", typeof(int), new Type[0], typeof(Program).Module);
    var ilGenerator = method.GetILGenerator();
    ilGenerator.Emit(OpCodes.Ldc_I4_S, 17);
    ilGenerator.Emit(OpCodes.Ldloca_S, 0);
    ilGenerator.Emit(OpCodes.Call, typeof(int).GetMethod(nameof(int.GetHashCode)));

    var delegateFunction = (Func<int>)method.CreateDelegate(typeof(Func<int>));

    var result = delegateFunction();
    Console.WriteLine($"Got {result}");

Share : facebook icon twitter icon

Call other method in IlGenerator

By : sarles
Date : March 29 2020, 07:55 AM
wish of those help From the source: (http://referencesource.microsoft.com/#mscorlib/system/reflection/emit/ilgenerator.cs,3e110f4a19d1c05e)
code :
public virtual void Emit(OpCode opcode, MethodInfo meth)
    if (opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))
        EmitCall(opcode, meth, null);
        // ...
for (byte x = 0; x < numParams; x++)
    il.Emit(OpCodes.Ldstr, x);
switch (numParams)
    case 0:
    case 1:
    case 2:
    case 3:
        for (int i = 4; i < numParams; i++)
            il.Emit(OpCodes.Ldarg, mb.GetParameters()[i]);
// Create field to back your "myImplementation" property
FieldBuilder newBackingField = tb.DefineField("backingField_myImplementation", typeof(MyInterface), System.Reflection.FieldAttributes.Private);
// Create your "myImplementation" property
PropertyBuilder newProp = tb.DefineProperty("myImplementation", System.Reflection.PropertyAttributes.None, typeof(MyInterface), Type.EmptyTypes);
// Create get-method for your property
MethodBuilder getter = tb.DefineMethod("get_myImplementation", System.Reflection.MethodAttributes.Private);
ILGenerator getterILGen = getter.GetILGenerator();
// Basic implementation (return backing field value)
getterILGen.Emit(OpCodes.Ldfld, newBackingField);

// Create set-method for your property
MethodBuilder setter = tb.DefineMethod("set_myImplementation", System.Reflection.MethodAttributes.Private);
setter.DefineParameter(1, System.Reflection.ParameterAttributes.None, "value");
ILGenerator setterILGen = setter.GetILGenerator();
// Basic implementation (set backing field)
setterILGen.Emit(OpCodes.Stfld, newBackingField);

// Hello1 Method
MethodBuilder hello1 = tb.DefineMethod("Hello1", System.Reflection.MethodAttributes.Public);
ILGenerator il = hello1.GetILGenerator();

// Here, add code to load arguments, if any (as shown previously in answer)

il.Emit(OpCodes.Call, getter);
il.Emit(OpCodes.Callvirt, typeof(MyInterface).GetMethod("Hello1"));

Call function directly vs emiting Signal (Qt - Signals and Slots)

By : Rajan Karol
Date : March 29 2020, 07:55 AM
like below fixes the issue Signals and slots are used to decouple classes so that they don't need to explicitly know who uses their functionality and how. In many cases, decoupling is a desirable trait of the design of your software. Of course it's not an end in itself, it's useful when it helps you to reason about the code's correctness and makes it easier to maintain. Decoupling help in understanding/reasoning about the code as it leads to smaller units of code that you can analyze in isolation. Another way to look at it is separation of concerns: let one unit of code do one thing, e.g. focus one class on one aspect of functionality.
When you have a pair of classes and wish to decide whether to couple them or not, think of whether they could be used with other classes. A could be coupled to B, but could the interface that couples the pair be used by C instead of B? If so, then some decoupling pattern must be used, and signal-slot pattern is one of them.
code :
class QObject {
  Q_SIGNAL void destroyed(QObject * obj = Q_NULLPTR);

class QObjectB {
  virtual void on_destroyed();

int main() {
  QObject a;
  struct ObjectB : QObjectB {
    void on_destroyed() override { qDebug() << "~QObjectB"; }
  } b;
  QObject::connect(&a, &QObject::on_destroyed, []{ qDebug() << "~QObject"; });

ILGenerator call method on field from property

By : user3467667
Date : March 29 2020, 07:55 AM
I hope this helps . An assignment is a little tricky.
You have to put this this pointer at very first place, the Ldarg_0, then comes the value you want to store and then the field you want to store to.
code :
1:LdArg0, So you put the this from PropertyField on the stack
2:LdArg0, you put the ThisPointer from _accessor on the stack
3:LdFld accessor, you load the accessor, remove one value from stack  from line (2)
4:LdArg0, you load the this pointer, this time your explicit parameter
5:LdLoc propertyInfo, you load your third parameter
6:Call load, // this will take 3 values from stack, lines (3)-(5)
7;Stfld propertyfield, // you store the property, on stack is the this pointer line(1) and the output of load line(6)

How to call a 'normal' method through ILGenerator.Emit*?

By : Ranz Prajapati
Date : March 29 2020, 07:55 AM
To fix this issue Is it possible for a DynamicMethod to call (via ILGenerator.EmitCall -- or similar -- for instance) a 'normal' method, e.g. Private Sub BlahBlah(ByVal obj as Object)?

ILGenerator call instance method with parameter

By : Alex Westphal blazze
Date : March 29 2020, 07:55 AM
Does that help You're confusing the boundary between the generated program, and the generating program.
Specifically, your generating program, when run, constructs an instance of an object (a MethodInfo instance) and then attempts to generate a program that uses that instance - which it can't because that instance doesn't exist in the generated program, it exists in the memory of the generating program.
Related Posts Related Posts :
  • JSON Deserialize is not working with List object
  • Convert Visual Studio 2017 C# solution / project for use with Mono on Linux?
  • Sort list by multiple variables
  • How valid is it to use `Result` inside `Task.Run`
  • how to put a variable in the image source in C# like we do in php
  • How to display an image stored in database as bytes into a View?
  • MVC issue for accessing the data from database:The parameters dictionary contains a null entry for parameter 'id' of non
  • Is there a method to group 4 controls into an UserControl or template and use it in parent UserControl and bind them wit
  • Xamarin Forms : can Prism and ReactiveUI be used in the same project ? If so, is it a good idea?
  • How can I paste the "plain" text of a string to int? C#
  • How to determine which table a column belongs to in an SQL Statement given metadata information and parse tree from SQL
  • How to fix The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statemen
  • AutoHotkey: Remap shortcut for MS Visio to align manually selected objects to the top (as if pressing: "AlignTop&qu
  • Can .csproj Switch native code by platform?
  • how to upload multiple files using a single upload control in a MVC application
  • How to use HttpClientFactory with AutoRest generated client
  • Parsing a phrase with Sprache(Words seperated by spaces)
  • called from Blazor client HttpClient.GetJsonAsync returns (with data), but then times out
  • Two processors can't log the information at the same time by using NLog
  • C# streamreader read data multiple times
  • Healthbar not decreasing when player is collided with the laser
  • Why are .cshtml changes are not reflected locally until app pool recycle? Why did building my project in Visual Studio s
  • How to make a specific order for calling methods?
  • Why OnCollisionEnter2D / OnTriggerEnter2D don't work?
  • how to use async and await so that it will create a different task or each request
  • Should unit tests tests the functionality of a method?
  • How to register singleton factory resolving scoped objects in ASP.NET Core?
  • How to use C# 6.0 or 7.0 in an old ASP.NET Website (not Website Project)
  • How to ensure that the WCF service will not communicate to the database in parallel
  • Removing items from LinkedList<>
  • Can you instantiate another class within the constructor?
  • Best way to instantiate a class with a private object that needs instantiating as well
  • C# Memory Issues
  • Should a input object be cloned if it is the return value?
  • How to pass c# decimal to sql decimal(4,2)
  • Blazor Component TwoWay Databinding
  • Is there a data structure in C# like a ConcurrentQueue which allows me to await an empty queue until an item is added?
  • how can I create sharepoint lists using c# without using DLLs like Microsoft.SharePoint.Client and Microsoft.SharePoint.
  • How to make Dispose await for all async methods?
  • Getting the `HttpContext` from a generic handler with an `HttpModule`
  • Entity Framework Core Use Include on QueryType(Database View)
  • Filter list of entity objects by string child object property using Linq Lambda
  • Does calling an async method immediately running its commands
  • Xamarin Forms/ReactiveUI Router - Show child View and execute parent ViewModel code after child View is closed
  • Unity - how do i move the pencil higher then the mouse
  • how to disable the button color in c#
  • I downloaded VS 2019 Enterprise. When I tried compile .net core 3.0 project, I got a problem
  • How to mock httpclient
  • Unable to read culture specific values
  • How a reference type can be assigned to a structure in c#
  • Instantiating a Prefab Without Inheriting Monobehaviour
  • How to p/Invoke a c++ executable into C#
  • Enum inside an enum
  • Using authProvider with MS SDK for graph calls in C#
  • How to adapt a C++ std::future return value to a C# System.Threading.Tasks.Task?
  • How to make two foreach "work" at the same time / parallel / async
  • visual studio 2019 version c# probleme
  • Replace 0 in array with "null" word in array
  • How to test this async delete method?
  • How to declare a table variable in SQL Server 2012 stored procedure?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk