Creating function pointers to functions created at runtime - c++

I would like to do something like:
for(int i=0;i<10;i++)
addresses[i] = & function(){ callSomeFunction(i) };
Basically, having an array of addresses of functions with behaviours related to a list of numbers.
If it's possible with external classes like Boost.Lambda is ok.
Edit: after some discussion I've come to conclusion that I wasn't explicit enough. Please read Creating function pointers to functions created at runtime
What I really really want to do in the end is:
class X
{
void action();
}
X* objects;
for(int i=0;i<0xFFFF;i++)
addresses[i] = & function(){ objects[i]->action() };
void someFunctionUnknownAtCompileTime()
{
}
void anotherFunctionUnknowAtCompileTime()
{
}
patch someFunctionUnknownAtCompileTime() with assembly to jump to function at addresses[0]
patch anotherFunctionUnknownAtCompileTime() with assembly to jump to function at addresses[1]
sth, I don't think your method will work because of them not being real functions but my bad in not explaining exactly what I want to do.

If I understand you correctly, you're trying to fill a buffer with machine code generated at runtime and get a function pointer to that code so that you can call it.
It is possible, but challenging. You can use reinterpret_cast<> to turn a data pointer into a function pointer, but you'll need to make sure that the memory you allocated for your buffer is flagged as executable by the operating system. That will involve a system call (LocalAlloc() on Windows iirc, can't remember on Unix) rather than a "plain vanilla" malloc/new call.
Assuming you've got an executable block of memory, you'll have to make sure that your machine code respects the calling convention indicated by the function pointer you create. That means pushing/popping the appropriate registers at the beginning of the function, etc.
But, once you've done that, you should be able to use your function pointer just like any other function.
It might be worth looking at an open source JVM (or Mono) to see how they do it. This is the essence of JIT compilation.

Here is an example I just hacked together:
int func1( int op )
{
printf( "func1 %d\n", op );
return 0;
}
int func2( int op )
{
printf( "func2 %d\n", op );
return 0;
}
typedef int (*fp)(int);
int main( int argc, char* argv[] )
{
fp funcs[2] = { func1, func2 };
int i;
for ( i = 0; i < 2; i++ )
{
(*funcs[i])(i);
}
}

The easiest way should be to create a bunch of boost::function objects:
#include <boost/bind.hpp>
#include <boost/function.hpp>
// ...
std::vector< boost::function<void ()> > functors;
for (int i=0; i<10; i++)
functors.push_back(boost::bind(callSomeFunction, i));
// call one of them:
functors[3]();
Note that the elements of the vector are not "real functions" but objects with an overloaded operator(). Usually this shouldn't be a disadvantage and actually be easier to handle than real function pointers.

You can do that simply by defining those functions by some arbitrary names in the global scope beforehand.

This is basically what is said above but modifying your code would look something like this:
std::vector<int (*) (int)> addresses;
for(int i=0;i<10;i++) {
addresses[i] = &myFunction;
}
I'm not horribly clear by what you mean when you say functions created at run time... I don't think you can create a function at run time, but you can assign what function pointers are put into your array/vector at run time. Keep in mind using this method all of your functions need to have the same signature (same return type and parameters).

You can't invoke a member function by itself without the this pointer. All instances of a class have the function stored in one location in memory. When you call p->Function() the value of p is stored somewhere (can't remember if its a register or stack) and that value is used as base offset to calculate locations of the member variables.
So this means you have to store the function pointer and the pointer to the object if you want to invoke a function on it. The general form for this would be something like this:
class MyClass {
void DoStuf();
};
//on the left hand side is a declaration of a member function in the class MyClass taking no parameters and returning void.
//on the right hand side we initialize the function pointer to DoStuff
void (MyClass::*pVoid)() = &MyClass::DoStuff;
MyClass* pMyClass = new MyClass();
//Here we have a pointer to MyClass and we call a function pointed to by pVoid.
pMyClass->pVoid();

As i understand the question, you are trying to create functions at runtime (just as we can do in Ruby). If that is the intention, i'm afraid that it is not possible in compiled languages like C++.
Note: If my understanding of question is not correct, please do not downvote :)

Related

How to do always the same things just before 'return' when a function has a lot of 'return's?

I've a big function which allocates 2 arrays in the heap memory and returns many times in many different places. I would like to make the function call delete[] for my 2 arrays whenever she returns, without having to write delete[]s before each return.
int function(int a)
{
size_t heap_arr1_len{100};
int* heap_arr1{new int[heap_arr1_len]};
size_t heap_arr2_len{200};
int* heap_arr2{new int[heap_arr2_len]};
//I was thinking of something similar to:
struct at_return{
~at_return()
{
delete[] heap_arr1;
delete[] heap_arr2;
}
} at_return;
/*...............
.................
......return 0;*/
/*...............
.....return 10;*/
//ecc.
}
but with a compilation-time error i've figured out that a struct can't access the local variables of the function which is contained in.
What would you do in order to avoid to having to write delete[] heap_arr1;, delete[] heap_arr2; each time before each return?
Don't allocate memory manually using new, use std::vector instead:
size_t heap_arr1_len = 100;
std::vector<int> heap_arr1(heap_arr1_len);
Then you don't need to worry about delete.
But using a destructor like this is in fact a great idea, assuming no suitable wrapper class exists. This trick is known as a scope guard. And here's a working implementation.
It could be useful e.g. when dealing with C libraries, which can't provide classes with destructors. You could write a reusable wrapper class with a destructor, or you could use a scope guard as an ad-hoc solution.
#include <memory>
int function(int a)
{
size_t heap_arr1_len{100};
std::unique_ptr<int[]> heap_arr1{new int[heap_arr1_len]};
// Etc
}
If you need the underlying pointer for your file reading/writing functions, use heap_arr1.get().
I use a can_continue method so there is only one entry and one exit (MISRA rule).
First set a Boolean variable:
bool can_continue = true;
The pattern then becomes:
if (can_continue)
{
// do some work
// set can_continue to false to return unexpectedly
}
It may not be the fastest code, but it meets the criteria for one entry and one exit.

Calling map function (Indirection requires pointer operand) [duplicate]

I'm trying to make a table of function pointers within a class. I haven't been able to find any examples of this online, most involve using member function pointers outside of their class.
for example:
class Test
{
typedef void (Test::*FunctionType)();
FunctionType table[0x100];
void TestFunc()
{
}
void FillTable()
{
for(int i = 0; i < 0x100; i++)
table[i] = &Test::TestFunc;
}
void Execute(int which)
{
table[which]();
}
}test;
Gives me the error "term does not evaluate to a function taking 0 arguments".
In this line in the Execute function:
table[which]();
You can't call it like that because it's not a normal function. You have to provide it with an object on which to operate, because it's a pointer to a member function, not a pointer to a function (there's a difference):
(this->*table[which])();
That will make the invoking object whichever object is pointed to by the this pointer (the one that's executing Execute).
Also, when posting errors, make sure to include the line on which the error occurs.
Seth has the right answer. Next time, look up the compiler error number on MSDN and you'll see the same: Compiler Error C2064.
You need a context in which to call your function. In your case, the context is this:
void Execute(int which)
{
(this->*table[which])();
}

Using member functions to deal with objects in the heap (c++)

I'm a beginner with C++, and this is a pretty basic syntax question, but i can't seem to find an answer elsewhere. Any input would be welcome. Here is a simplified version of the problem.
Say I have a class 'pair'
class pair
{
int a;
int b;
public:
pair(int x,int y)
{
a=x;
b=y;
}
int lookup()
{
return this->a+b;
}
};
Then i instanciate and copy that instance to a spot on the heap.
int func()
{
...
pair test(1,2);
pair *ptr=new pair;
*ptr=test;
}
Now here is the key. I don't destroy this memory allocation after the function ends. I want to use it later in this other function. The problem is, i would prefer to keep it in the heap and NOT have to copy it over to the stack(in the actual program it is very large). I would therefore like to do something like this:
int otherfunc()
{
...
int sum=*ptr.lookup;
}
but I get a compiler error. I end up having to do something like:
int otherfunc()
{
...
point temp=*ptr;
int sum=temp.lookup;
}
While this works, it is redundant, and when dealing with really large things it can even potentially cause an overflow. Anyone know the syntax for calling the method using the pointer while keeping it on the heap? Thanks.
I believe this is what you are trying to do:
int sum = ptr->lookup();
And as an aside, this:
return this->a+b;
Would probably be better as just this:
return a+b;
The expression *ptr.lookup will be interpreted as *(ptr.lookup), which is why you get the syntax error because ptr.lookup does not make sense. You'll need to tell the compiler dereference ptr first by using the parenthesis: (*ptr).lookup.
Because pointers are common in C (and C++), the (*a).b can be written in a simpler form: a->b.
Also, lookup is a function even if it does not take any parameters. You need to call it with ():
int sum=ptr->lookup();

std::map, storing pointer (to object) by pointer (to some object's related struct). Which types to use?

To overcome the impossibility of giving C library a callback to C++ member function, wanted to implement something like this:
SomeObject* findSomeObjectByHandlePointer(datahandle *dh) { }..
by using a map, which contains addresses of *datahandle as an index, and addresses of *SomeObject's as value.
When SomeObject is created, it produces a group of datahandle's, which are unique for the object. Then, it passes a pointer to *datahandle and static callback function to C library, then C library calls back and returns a pointer to datahandle, that in turn can be associated back with a SomeObject.
Which types can you recommend for storing pointer values in a map besides safe but slow <string, SomeObject*>?
This answer tells me to avoid using auto_ptr too.
Normally, C-like callbacks take a void* user_data parameter, which allows you to pass in anything you want:
void c_func(void (*fptr)(void*), void* user_data){
// do some stuff
fptr(user_data);
}
Now, simply make the following static member function:
class A{
public:
static void c_callback(void* my_data){
A* my_this = static_cast<A*>(my_data);
// do stuff with my_this
}
};
Edit: According to #Martin's comment, you may get unlucky with a static member function. Better use an extern "C" function:
extern "C" void c_callback(void* my_data){
// same as static method
}
And pass that + your A instance to that c_func:
int main(){
A a;
c_func(&A::c_callback,&a);
}
Or if that A instance needs to outlive the current scope, you need to somehow save the heap-allocated pointer somewhere and delete it manually later on. A shared_ptr or the likes won't work here, sadly. :(
On your problem of storing pointer in a map, that's not a problem at all, see this little example on Ideone.
I think this will suffice. It is what we use:
class datahandle;
class SomeObject;
typedef std::map<datahandle*, SomeObject*> pointer_map;
pointer_map my_map;
SomeObject* findSomeObjectByHandlePointer( datahandle *dh) {
pointer_map::const_iterator ff = my_map.find(dh);
if (ff != my_map.end()) {
return ii->second;
}
return NULL;
}
Often callback functions have an extra parameter of type void* which you can use to pass in any additional data you might need. So if you want to use a member function as your callback, you pass in a pointer to the object casted to void* and then cast it back and call the member function in your callback function.
If you have many reads and less writes, you could use vector as a set. It is very common, because lower_bound is more effective than map and use less space from memory:
typedef std::pair<std::string,Your_pointer> your_type;
bool your_less_function( const your_type &a, const your_type &b )
{
// your less function
return ( a < b );
}
...
std::vector<your_type> ordered-vector;
When you add values:
...
ordered-vector.push_back(value)
...
// Finally. The vector must be sorted before read.
std::sort( ordered-vector.begin(), ordered-vector.end(), your_less_function );
When ask for data:
std::vector<your_type>::iterator iter = std::lower_bound( ordered-vector.begin(), ordered-vector.end(), value, your_less_function );
if ( ( iter == ordered-vector.end() ) || your_less_function( *iter, value ) )
// you did not find the value
else
// iter contains the value

Is qsort thread safe?

I have some old code that uses qsort to sort an MFC CArray of structures but am seeing the occasional crash that may be down to multiple threads calling qsort at the same time. The code I am using looks something like this:
struct Foo
{
CString str;
time_t t;
Foo(LPCTSTR lpsz, time_t ti) : str(lpsz), t(ti)
{
}
};
class Sorter()
{
public:
static void DoSort();
static int __cdecl SortProc(const void* elem1, const void* elem2);
};
...
void Sorter::DoSort()
{
CArray<Foo*, Foo*> data;
for (int i = 0; i < 100; i++)
{
Foo* foo = new Foo("some string", 12345678);
data.Add(foo);
}
qsort(data.GetData(), data.GetCount(), sizeof(Foo*), SortProc);
...
}
int __cdecl SortProc(const void* elem1, const void* elem2)
{
Foo* foo1 = (Foo*)elem1;
Foo* foo2 = (Foo*)elem2;
// 0xC0000005: Access violation reading location blah here
return (int)(foo1->t - foo2->t);
}
...
Sorter::DoSort();
I am about to refactor this horrible code to use std::sort instead but wondered if the above is actually unsafe?
EDIT: Sorter::DoSort is actually a static function but uses no static variables itself.
EDIT2: The SortProc function has been changed to match the real code.
Your problem doesn't necessarily have anything to do with thread saftey.
The sort callback function takes in pointers to each item, not the item itself. Since you are sorting Foo* what you actually want to do is access the parameters as Foo**, like this:
int __cdecl SortProc(const void* elem1, const void* elem2)
{
Foo* foo1 = *(Foo**)elem1;
Foo* foo2 = *(Foo**)elem2;
if(foo1->t < foo2->t) return -1;
else if (foo1->t > foo2->t) return 1;
else return 0;
}
Your SortProc isn't returning correct results, and this likely leads to memory corruption by something assuming that the data is, well, sorted after you get done sorting it. You could even be leading qsort into corruption as it tries to sort, but that of course varies by implementation.
The comparison function for qsort must return negative if the first object is less than the second, zero if they are equal, and positive otherwise. Your current code only ever returns 0 or 1, and returns 1 when you should be returning negative.
int __cdecl Sorter::SortProc(const void* ap, const void* bp) {
Foo const& a = *(Foo const*)ap;
Foo const& b = *(Foo const*)bp;
if (a.t == b.t) return 0;
return (a.t < b.t) ? -1 : 1;
}
C++ doesn't really make any guarantees about thread safety. About the most you can say is that either multiple readers OR a single writer to a data structure will be OK. Any combination of readers and writers, and you need to serialise the access somehow.
Since you tagged your question with MFC tag I suppose you should select Multi-threaded Runtime Library in Project Settings.
Right now, your code is thread-safe, but useless, as the DoSort-method only uses local variables, and doesn't even return anything. If the data you are sorting is a member of Sorter, then it is not safe to call the function from multiple threads. In gerenal, read up on reentrancy, this may give you an idea of what you need to look out for.
what make it thread safe is, whether your object are thread safe, for example to make qsort thread-safe you must ensure that anything that write or read to or from and to the object are thread safe.
The pthreads man page lists the standard functions which are not required to be thread-safe. qsort is not among them, so it is required to be thread-safe in POSIX.
http://www.kernel.org/doc/man-pages/online/pages/man7/pthreads.7.html
I can't find the equivalent list for Windows, though, so this isn't really an answer to your question. I'd be a bit surprised if it was different.
Be aware what "thread-safe" means in this context, though. It means you can call the same function concurrently on different arrays -- it doesn't mean that concurrent access to the same data via qsort is safe (it isn't).
As a word of warning, you may find std::sort is not as fast as qsort. If you do find that try std::stable_sort.
I once wrote a BWT compressor based on the code presented my Mark Nelson in Dr Dobbs and when I turned it into classes I found that regular sort was a lot slower. stable_sort fixed the speed problems.