79267399

Date: 2024-12-10 08:03:29
Score: 1
Natty:
Report link

After discussing with CharlieFace in the comments, I learned that what I wanted to achieve can be done without using C++. I want to thank everyone who contributed.

If you found this thread and came here, I recommend reading the comments. They will likely solve your C++ problem as well.

The code that solved my issue is as follows:

using System.Linq.Expressions;
using System.Reflection;

public struct MyStruct
{
    public string name;
}

public class Program
{
    public void FunctionCreatedByUser(int x, float anything, string name, MyStruct myStruct)
    {
        Console.WriteLine($"{x}  {anything}  {name}" + "   " + myStruct.name);
    }

    static void Main()
    {
        Program program = new Program();

        var parameters = new object[] { 10, 20.5f, "TestName", new MyStruct() { name = "asdagdjakfadgkjdhflajg" } };

        MethodInfo methodInfo = typeof(Program).GetMethod("FunctionCreatedByUser");

        var lambdaParam = Expression.Parameter(typeof(object[]), "parameters");

        var methodParams = methodInfo.GetParameters();
        var convertedParams = new Expression[methodParams.Length];
        for (int i = 0; i < methodParams.Length; i++)
        {
            var paramAccess = Expression.ArrayIndex(lambdaParam, Expression.Constant(i));
            convertedParams[i] = Expression.Convert(paramAccess, methodParams[i].ParameterType);
        }

        var methodCall = Expression.Call(
            Expression.Constant(program),  // Instance of the class
            methodInfo,                    // Method to call
            convertedParams                // Parameters for the method
        );

        var lambda = Expression.Lambda<Action<object[]>>(methodCall, lambdaParam);

        Action<object[]> compiledDelegate = lambda.Compile();
        compiledDelegate(parameters);
    }
}

Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Bilal