How to Create a Function Dynamically, During Runtime in C++

Can I dynamically build a function at runtime in c#?

(Updated)
This example builds and compiles a function that varies based on the results you passed in.

    public static object CallFunction(object item) { return item; }
public static object AnotherFunctionCall(object item) { return item; }
public static object ThirdFunctionCall(object item) { return item; }

public static MethodInfo CallFunctionMethodInfo = typeof(BuildFunction).GetMethod("CallFunction");
public static MethodInfo AnotherFunctionCallMethodInfo = typeof(BuildFunction).GetMethod("AnotherFunctionCall");
public static MethodInfo ThirdFunctionCallMethodInfo = typeof(BuildFunction).GetMethod("ThirdFunctionCall");

public static Func<object, object> CreateFunc(bool boolA, bool boolB)
{
var objectParameter = Expression.Parameter(typeof(object));
var returnVar = Expression.Variable(typeof(object), "returnVar");

var commands = new List<Expression>();

commands.Add(
Expression.Assign(
returnVar,
Expression.Call(CallFunctionMethodInfo, objectParameter)));

if (boolA)
{
commands.Add(
Expression.Assign(
returnVar,
Expression.Call(AnotherFunctionCallMethodInfo, returnVar)));
}

if (boolB)
{
commands.Add(
Expression.Assign(
returnVar,
Expression.Call(ThirdFunctionCallMethodInfo, returnVar)));
}

commands.Add(returnVar);

var body = Expression.Block(new[] { returnVar }, commands);

return Expression.Lambda<Func<object, object>>(body, objectParameter).Compile();
}

Call this function from your code Func<object, object> processor = CreateFunc(boolA,boolB);

Creating a function dynamically at run-time

The easiest way to do it is probably DLINQ as TcKs suggested.

The fastest (I believe, in 3.5) is to create a DynamicMethod. Its also the scariest method as well. You're essentially building a method using IL, which has about the same feel as writing code in machine language.

I needed to do this to dynamically attach event handlers in some thing or another (well, I didn't need to do it, I just wanted to make unit testing events easier). It seemed a bit daunting at the time because I don't know crap about IL, but I figured out a simple way to accomplish this.

What you do is create a method that does exactly what you want. The more compact the better. I'd provide an example if I could figure out exactly what you're trying to do. You write this method in a class within a DLL project and compile it in release mode. Then you open the DLL in Reflector and disassemble your method. Reflector gives you the option of what language you wish to disassemble to--select IL. You now have the exact calls you need to add to your dynamic method. Just follow the example on MSDN, switching out the example's IL for your reflected methods' code.

Dynamic methods, once constructed, invoke at about the same speed as compiled methods (saw a test where dynamic methods could be called in ~20ms where reflection took over 200ms).

Dynamic Function in Cpp

I tried to create a solution using function templates.

The two main functions are GetMyFunction() and MyFunctionTemplate().

MyFunctionTemplate() is a function template which would accept all of your expected params as bool template arguments(Non-type Template Arguments).

GetMyFunction() function would return pointer to the required specialization of MyFunctionTemplate() during run time.

GetMyFunction() also does one more thing, it must check for all of the combinations of the params, and return the corresponding function.

These MyFunctionTemplate() specialization would be created during compile time, and I believe those if() checks within MyFunctionTemplate() would be removed since those are time compile-time constants(Someone please confirm this).

#include <iostream>

using namespace std;

void aFunc() { cout << "in a()" << endl; }
void bFunc() { cout << "in b()" << endl; }
void cFunc() { cout << "in c()" << endl; }
void dFunc() { cout << "in d()" << endl; }

template <bool a, bool b, bool c, bool d>
void MyFunctionTemplate()
{
if (a) aFunc();
if (b) bFunc();
if (c) cFunc();
if (d) dFunc();
}

void (*GetMyFunction(bool a, bool b, bool c, bool d))()
{
if (a && b && c && d)
return &MyFunctionTemplate<true, true, true, true>;
if (a && b && c && !d)
return &MyFunctionTemplate<true, true, true, false>;
// And all other combinations follows....
}

int main(void)
{
// Conditions A - I is declared here
bool a = true, b = true, c = true, d = true;
// auto MyFunction = GetMyFunction(a, b, c, d);
void (*MyFunction)(void) = GetMyFunction(a, b, c, d);
MyFunction();

return 0;
}

How could i define a function at run-time in c

I think, you can enter the opcodes directly in a string "binary-code" and execute the code using ((void*)STRING)(). However, you may want to read also about how gcc implements trampolines, because this is how gcc generates code that creates code on the stack and jumps the execution there.

C++ Dynamically Define Function

What you need (in addition to a script language interpreter) is called a "trampoline". There is no standard solution to create those, in particular since it involves creating code at runtime.

Of course, if you accept a fixed number of trampolines, you can create them at compile time. And if they're all linear, this might be even easier:

const int N = 20; // Arbitrary
int m[N] = { 0 };
int b[N] = { 0 };
template<int I> double f(double x) { return m[I] * x + b; }

This defines a set of 20 functions f<0>...f<19> which use m[0]...m[19] respectively.

Edit:

// Helper class template to instantiate all trampoline functions.
double (*fptr_array[N])(double) = { 0 };
template<int I> struct init_fptr<int I> {
static const double (*fptr)(double) = fptr_array[I] = &f<I>;
typedef init_fptr<I-1> recurse;
};
template<> struct init_fptr<-1> { };


Related Topics



Leave a reply



Submit