I have a DLL which has a function which accepts a function pointer converts it to a boost::function. This is then stored and then called from inside the DLL.
I want to add a function to the DLL to handle member functions in a similar way. I know I need to use boost::bind to wrap the member function pointer and the object together. I want to do the binding on the DLL side though so the EXE does not require boost libraries to be included.
How would you write this function? One which accepts a member function pointer and an object as arguments and binds them together.
Thanks!
you're warned by #Kylotan, so you can try something like this:
__declspec(dllexport) void store_mem_fn(void(Your_class::*mem_fn)(void), Your_class& instance)
{
std::vector<boost::function<void(void)> > container;
container.push_back(boost::bind(mem_fn, instance));
}
It might be a bad idea to try passing member function pointers into DLLs because they can vary in size depending on certain circumstances. (Some details here.) Maybe if you always know that you will be building both halves of the application with the same compiler you will be ok.
As for the function, I expect it would look something like this (completely untested and uncompiled code):
typedef void(ObjectType::*OTMemberFn)();
boost::function<void (ObjectType o)> bind_mem_fn(ObjectType o, OTMemberFn mf)
{
return boost::bind(mf, o);
}
Isn't Boost open source? If so, peek into the boost code, learn how it's done, and re-implement it yourself, without the dependency.
Related
So here's the situation: I'm using C++, SDL and GLConsole in conjunction. I have a class, SDLGame, which has the Init(), Loop(), Render() etc - essentially, it holds the logic for my game class.
GLConsole is a nice library so far - it lets me define CVars and such, even inside my SDL class. However, when defining commands, I have to specify a ConsoleFunc, which is typedef'd as
typedef bool (*ConsoleFunc)( std::vector<std::string> *args);
Simple enough. However, like I said, my functions are all in my class, and I know I can't pass pointer-to-class-functions as pointer-to-function arguments. I can't define static functions or make functions outside my class because some of these ConsoleFuncs must access class data members to be useful. I'd like to keep it OOP, since - well, OOP is nice.
Well, I actually have this problem "solved" - but it's extremely ugly. I just have an instance of SDLGame declared as an extern variable, and use that in my ConsoleFuncs/main class.
So, the question is: Is there a way to do this that isn't stupid and dumb like the way I am doing it? (Alternatively: is there a console library like GLConsole that supports SDL and can do what I'm describing?)
If the only interface you have is that function pointer, then you're screwed.
A member function needs a this pointer to be called, and if you have no way of passing that, you're out of luck (I guess the std::vector<std::string>* args pointer is what you get passed from the library).
In other words, even though that library uses C++ containers, it's not a good C++ library, because it relies on free functions for callbacks. A good C++ library would use boost::function or something similar, or would at the very least let you pass a void* user_data pointer that gets passed through to your callback. If you had that, you could pass the this pointer of your class, cast it back inside the callback, and call the appropriate member function.
Apologies in advance for noob mistakes. This is my first question here. First, some background:
I am trying to create a module for a program using dependency walker to find C++ functions in a .dll that I don't have the lib or any source code for. You can also assume that I can't get support from the original developer. Basically, I checked another file that accesses it to see what the minimum functions were to get it working. Here is an example of the undecorated names that are output:
void foo::bar::baz(float)
float foo::bar::qux(void)
foo::bar::bar(void)
class foo::bar & foo::bar::operator=(class foo::bar const &)
The top two functions obviously take float or void and return float or void. I got a similar function working using something like:
HINSTANCE THEDLL = LoadLibrary("C:\\dllFolder\\theDll.dll");
typedef float (*quxType)(void);
quxType qux = (quxType)GetProcAddress(THEDLL, "quxMangledName");
So those are not a problem.
Now, the third on the list looks like another function that takes void, but it doesn't have an explicit return type. Does this mean I should just use an implicit type for it, is it void, or is it not really a function? If not, what is it?
I have no idea what to do with the fourth one. Is it even possible to handle without the associated .h file?
I looked around, but I couldn't find any information on what to do when the function doesn't look like a normal function with an explicit return type. Despite using basically the same code that I used to get a function working in a similar .dll, I keep getting an access violation crash when I try to use function #2 here (I really just need function #2). So I am guessing that the .dll needs more information or needs something initialized first, which is why I am interested in the others on the list.
I realize this is a complicated problem, so there probably won't be a "Right answer" solution to get it working, but if I am making any obvious mistakes, or if there are any general suggestions for how to attack the problem (even alternatives to dependency walker), let me know.
The 3rd one is the default constructor of bar.
The 4th one is the copy assignment operator of bar.
I think you need to instantiate the class first, in order to call the 2nd method. Otherwise the method would be called with an invalid 'this' that causes access violation.
The problem is how you instantiate it?
If you can find a factory function that returns a bar in the DLL, you can try to use it.
If you don't see a factory function and you don't have the lib file, you can refer to answers here on how to create a lib from a DLL: How to make a .lib file when have a .dll file and a header file
You also need to create header file for the class, with the correct order and types of members. This way you don't have to use LoadLibrary and GetProcAddress, just use the class as normal.
You may still use LoadLibrary and GetProcAddress without the lib and header though, this blog shows how to manually allocate memory, call constructor, gets an object and pass that object to call a method: http://recxltd.blogspot.com/2012/02/working-with-c-dll-exports-without.html
So here's the situation: I'm using C++, SDL and GLConsole in conjunction. I have a class, SDLGame, which has the Init(), Loop(), Render() etc - essentially, it holds the logic for my game class.
GLConsole is a nice library so far - it lets me define CVars and such, even inside my SDL class. However, when defining commands, I have to specify a ConsoleFunc, which is typedef'd as
typedef bool (*ConsoleFunc)( std::vector<std::string> *args);
Simple enough. However, like I said, my functions are all in my class, and I know I can't pass pointer-to-class-functions as pointer-to-function arguments. I can't define static functions or make functions outside my class because some of these ConsoleFuncs must access class data members to be useful. I'd like to keep it OOP, since - well, OOP is nice.
Well, I actually have this problem "solved" - but it's extremely ugly. I just have an instance of SDLGame declared as an extern variable, and use that in my ConsoleFuncs/main class.
So, the question is: Is there a way to do this that isn't stupid and dumb like the way I am doing it? (Alternatively: is there a console library like GLConsole that supports SDL and can do what I'm describing?)
If the only interface you have is that function pointer, then you're screwed.
A member function needs a this pointer to be called, and if you have no way of passing that, you're out of luck (I guess the std::vector<std::string>* args pointer is what you get passed from the library).
In other words, even though that library uses C++ containers, it's not a good C++ library, because it relies on free functions for callbacks. A good C++ library would use boost::function or something similar, or would at the very least let you pass a void* user_data pointer that gets passed through to your callback. If you had that, you could pass the this pointer of your class, cast it back inside the callback, and call the appropriate member function.
I would like to make an alias in C++ to singleton calling
so instead of calling MYCLASS::GetInstance()->someFunction(); each time, I could call just someFunctionAlias(); in my code.
Use a static function.
namespace ... {
void someFunction() {
MYCLASS::GetInstance()->someFunction();
}
};
Edit: Sorry lads, I wrote static someFunction and meant void someFunction.
typedefs are used for type aliases but can't be used as call alias.
functions (such as suggested as by DeadMG) can be used as a call "alias".
PS. As this is C++ you have lots of options, function pointers, std::tr1::function<> operator overloading and the preprocessor. But in this case it certainly looks like a simple function would be the simplest and best solution.
Look up function pointers.
You can create a function pointer, and assign it to your long function. You can then call this function pointer just like a regular function, wherever your variable is defined.
Function pointers can be confusing, but are used a lot in API callbacks (i.e. you pass a function as an argument to the API, and the API will call that function when something happens (think WndProc)).
Good luck.
you can do this
#define someFunctionAlias MYCLASS::GetInstance()->someFunction()
in C++, I can easily create a function pointer by taking the address of a member function. However, is it possible to change the address of that local function?
I.e. say I have funcA() and funcB() in the same class, defined differently. I'm looking to change the address of funcA() to that of funcB(), such that at run time calling funcA() actually results in a call to funcB(). I know this is ugly, but I need to do this, thanks!
EDIT----------
Background on what I'm trying to do:
I'm hoping to implement unit tests for an existing code base, some of the methods in the base class which all of my modules are inheriting from are non-virtual. I'm not allowed to edit any production code. I can fiddle with the build process and substitute in a base class with the relevant methods set to virtual but I thought I'd rather use a hack like this (which I thought was possible).
Also, I'm interested in the topic out of technical curiosity, as through the process of trying to hack around this problem I'm learning quite a bit about how things such as code generation & function look-up work under the hood, which I haven't had a chance to learn in school having just finished 2nd year of university. I'm not sure as to I'll ever be taught such things in school as I'm in a computer engineering program rather than CS.
Back on topic
The the method funcA() and funcB() do indeed have the same signature, so the problem is that I can only get the address of a function using the & operator? Would I be correct in saying that I can't change the address of the function, or swap out the contents at that address without corrupting portions of memory? Would DLL injection be a good approach for a situation like this if the functions are exported to a dll?
No. Functions are compiled into the executable, and their address is fixed throughout the life-time of the program.
The closest thing is virtual functions. Give us an example of what you're trying to accomplish, I promise there's a better way.
It cannot be done the way you describe it. The only way to change the target for a statically bound call is by modifying the actual executable code of your program. C++ language has no features that could accomplish that.
If you want function calls to be resolved at run-time you have to either use explicitly indirect calls (call through function pointers), or use language features that are based on run-time call resolution (like virtual functions), or you can use plain branching with good-old if or switch. Which is more appropriate in your case depends on your specific problem.
Technically it might be possible for virtual functions by modifying the vtable of the type, but you most certainly cannot do it without violating the standard (causing Undefined Behavior) and it would require knowledge of how your specific compiler handles vtables.
For other functions it is not possible because the addresses of the functions are directly written to program code, which is generally on a read-only memory area.
I am fairly sure this is impossible in pure C++. C++ is not a dynamic language.
What you want is a pointer to a function, you can point it to FuncA or FuncB assuming that they have the same signature.
You cannot do what you want to do directly. However, you can achieve a similar result with some slightly different criteria, using something you are already familiar with -- function pointers. Consider:
// This type could be whatever you need, including a member function pointer type.
typedef void (*FunctionPointer)();
struct T {
FunctionPointer Function;
};
Now you can set the Function member on any given T instance, and call it. This is about as close as you can reasonably get, and I presume that since you are already aware of function pointers you're already aware of this solution.
Why don't you edit your question with a more complete description of the problem you're trying to solve? As it stands it really sounds like you're trying to do something horrible.
Its simple!
For
at run time calling funcA() actually results in a call to funcB().
write funcA() similar to following:
int funcA( int a, int b) {
return funcB( a, b );
}
:-)