bharat
bharat

Reputation: 29

change the C function contents at run-time

I have a use-case in which the function contents are to be selected conditionally. And that function pointer is passed to other module for later invocation.

void encode_function(int flag)
{
 if (flag == 1)
  encode1();
 if (flag == 2)
  encode2();

  encode_defaults();
}

Once the encode_function() is populated, I will pass it to other module, where it will be invoked. I am trying to achieve it in C language, but no success so far. I tried to look at dyncall library but it supports only dynamic parameter changes.

I am looking for something which allows me to change the function contents at run-time.

Some existing question Is there a way to modify the code of a function in a Linux C program at runtime?

Upvotes: 0

Views: 1485

Answers (1)

miushock
miushock

Reputation: 1097

You are basically looking for the ability to treat code as data, which is a feature rarely available in compiled imperative static languages like c. The capability of modifying functions at run time is generally categorized as high order functions (you're basically trying to return a function as data somewhere in the code).

If the problem can be solved by several static functions, you can pass in function pointers to different implementations, otherwise I think c does not have the ability to really treat code as data and modify them on the fly.

This question makes attempt to implement high order function in c, but going this far might not be what you want.

Upvotes: 3

Related Questions