I am converting fortran code to C++ and wanted to find a right option for function-pointer.
The fortran code is: for two different cases, it passes two different kinds of function-pointers to another function. These function pointers have different interfaces. In C++, I need to specify interface of function-pointer and hence it is not straightforward. Can someone suggest, if C++ functor or something else, that would be useful? I wish I could use something like 'void (function) pointer' and then 'cast', but I really don't know. Thanks in advance.
EDIT: minimal example in fortran
Fortran
if(option1) then
call myfunc( abc_function_pointer,otherarguments)
else
call myfunc( xyz_function_pointer, otherarguments)
endif
where, these functions are (in C++)
void (*abc_function_pointer)(int, float) //in c++
void (*xyz_function_pointer)(int, int, int) //in c++
Generally speaking, this is a bad idea. Consider - what is myfunc going to do with this function pointer? What happens if you pass it abc_function_pointer, but it tries to call it with three ints? Or vice versa?
Without knowing what you're using this for, it's hard to suggest what you should do. Typically you would want to factor out the common interface between abc_function_pointer and xyz_function_pointer, so myfunc always calls a function with the same type and interface. You can insert a shim function that converts between the common interface and that of abc_function_pointer or xyz_function_pointer.
Related
I'm calling a function with __func__ as one of the parameters so I can store the name of the function calling that function without having to retype the name of the calling function.
Is there a way of also getting the address of the calling function - a sort of getaddress(__func __) ??
The address will not tell you much; may I instead suggest the predefined macros __FILE__ and __LINE__? They will tell you the current source file (as a char*) and the current line. When you call a function passing those as parameters, you'd know which file/line was the function called from.
They're evaluated by the compiler at the point of usage. If you use them inside the function as opposed to passing them as parameters, they'll tell you the file/line of the function itself.
You can declare function pointers and then assign specific functions to them. So then you could have an array or other collection of such pointers as your table.
If this works for you and you accept the answer, I'm willing to come back and create a short summary here. (I know I'm not supposed to answer with just-a-link.) But see if this approach will do what you want.
https://www.learncpp.com/cpp-tutorial/78-function-pointers/
There is no portable standard C++ way to do this. You could use compiler/OS specific hacks, the same was as in C, but it's less useful in C++ since it only works on extern "C" names (where the __FUNCTION__/__func__ match what dlsym expects).
Since that hack only works on extern "C" names, this means you can't use it for templated functions, class methods, or function overloading (same function name, different argument prototypes), which is fairly restrictive. Mind you, even typing out the function name wouldn't work in some of those cases already (e.g. the name alone doesn't describe the prototype, so function overloading wouldn't work).
I think you need to rethink a design that's essentially demanding reflection in C++; the nature of optimizing compilers is that most of the functions you define don't actually have to exist, or if they do, they exist only with names that are meaningless to anything but the compiler. When you ask to dynamically determine the address of the current function from within the function, you're assuming the function exists, with an actual address, in the final compiled binary, when it could just as easily have been inlined into each actual call site, partially merged with a near identical function, etc.
Is there any way a C++ beginner can implement something like this? For example:
./timerprogram sortalgorithm.cpp
where timerprogram.cpp at some point does something like argv[1](); to run the function whose name is given by the command-line argument?
Assuming that sortalgorithm.cpp was self-contained and had an array to sort already. I don't need the timing part, just how to call as a function a command-line argument. Is there anything build-in to C++ that will allow me to do this?
No. The answer is no.
Most of the stuff you see about this are inside jokes.
There are silly ways to make it look like its working, but they are silly, and certainly not for beginners.
Function names are used mostly by the compiler, to compile the code, and figure out when something calls a function "where" it actually is. Also by the linker too, but that's beside the point.
Although some C++ implementations might provide run-time extensions or libraries that can be used to resolve an address given its symbol name, the easiest and the most portable solution is for your program to simply have an array of strings, with your function names, and a pointer to the corresponding function.
Then, your main() searches the array for the requested function name, and invokes it via its function pointer.
How to implement this simple solution is going to be your homework assignment.
Suppose I have a dll with 2 functions.name of dll="dll1"
f1(int a, int b, int c);
f2(int a);
My program would take the function name ,the dll name and a "list" of parameters as input.
how would i call the appropriate function with its appropriate parameters.
i.e,
if input is
dll1
f1
list(5,8,9)
this would require me to call f1 with 3 parameters
if input was
dll1
f2
list(8)
it would require me to call f2 with one parameter
how would i call the function without knowing the number of parameters in advance.
further clarification:
how do I write code that will call any
function with all its arguments by building the argument list dynamically
using some other source of information
Since the generated code differs based on the number of parameters, you have two choices: you can write some code in assembly language to do the job (basically walk through the parameter list and push each on the stack before calling the function), or you can create something like an array of pointers to functions, one for each number of parameters you care about (e.g., 0 through 10). Most people find the latter a lot simpler to deal with (if only because it avoids using assembly language at all).
To solve the problem in general you need to know:
The calling conventions (those stdcall, cdecl, fastcall, thiscall (btw, the latter two can be combined in MSVC++), etc things) that govern how the functions receive their parameters (e.g. in special registers, on the stack, both), how they return values (same) and what they are allowed to trash (e.g. some registers).
Exact function prototypes.
You can find all this only in the symbol/debug information produced by the compiler and (likely to a lesser extent) the header file containing the prototypes for the functions in the DLL. There's one problem with the header file. If it doesn't specify the calling convention and the functions have been compiled with non-default calling conventions (via a compiler option), you have ambiguity to deal with. In either case you'll need to parse something.
If you don't have this information, the only option left is reverse engineering of the DLL and/or its user(s).
In order to correctly invoke an arbitrary function only knowing its prototype and calling convention at run time you need to construct code analogous to that produced by the compiler when calling this function when it's known at compile time. If you're solving the general problem, you'll need some assembly code here, not necessarily hand-written, run-time generated machine code is a good option.
Last but not least, you need some code to generate parameter values. This is most trivial with numeric types (ints, floats and the like) and arrays of them and most difficult with structures, unions and classes. Creating the latter on the fly may be at least as difficult as properly invoking functions. Don't forget that they may refer to other objects using pointers and references.
The general problem is solvable, but not cheaply. It's far easier to solve a few simple specific cases and maybe avoid the entire problem altogether by rewriting the functions to have less-variable parameters and only one calling convention OR by writing wrapper functions to do that.
You might want to check out the Named Parameter Idiom.
It uses method chaining to basically accomplish what you want.
It solves the problem where you know what a default set of arguments look like, but you only need to customize a few of them and not necessarily in the order they are declared.
If your clients know at compile-time, then can wrap it this way:
template<class Args...>
void CallFunctionPointer(void* pf, Args&&... args)
{
typedef void(*FunctionType)(Args...);
FunctionType* pf2 = (FunctionType*) pf;
(*pf2)(forward<Args>(args)...);
}
Note, if you pass the wrong number of paramters or the wrong type(s) of parameters behaviour is undefined.
Background:
In C/C++ you can cast a function pointer to any signature you want, however if you get it wrong behavior is undefined.
In your case there are two signatures you have mentioned:
void (*)(int)
and
void (*)(int, int, int)
When you load the function from the DLL it is your responsibility to make sure you cast it to the correct signature, with the correct number and types of parameters before you call it.
If you have control over the design of these functions, I would modify them to take a variable number of arguments. It the base type is always int, than just change the signature of all the functions to:
void (*)(int* begin, size_t n);
// begin points to an array of int of n elements
so that you can safely bind any of the functions to any number of arguments.
I'm working on a project with openGL, and I want to wrap all the C function, function pointers with a higher level of abstraction using C++ STL and boost. I checked boost::function, but it was designed to work with functor instead of function pointers. I wonder if there is a C++ idiom help to wrap C function calls instead of using it globally. Any idea?
Thanks,
Chan
Boost Function also works with function pointers see http://www.boost.org/doc/libs/1_45_0/doc/html/function/tutorial.html#id1264511
boost::function works perfectly well with function pointers. It can operate on any type with an operator() of the correct signature- including function pointers.
I posted this Q to TI's 28xx DSP forum but haven't heard a response and figured maybe someone here might know.
I know how to write functions in assembly so that they are C-callable; if the C-callable name is foo() then the assembly function is named _foo().
What if I want to use C++ and optimize a class method in assembly? How do I do that? I assume the only major issues are:
naming
accessing the "this" pointer
accessing class members by somehow knowing offsets
and if I don't want to worry about the last two, then perhaps I would write a static member function and do this:
class MyClass
{
int x;
static int _doSomething(int u); // implement this in assembly
public:
inline void doSomething() { x = _doSomething(x); }
// lightweight C++ wrapper to handle the class member / "this" pointer stuff
};
The this pointer gets passed as an additional argument to the function, using the standard calling convention on your platform. On all the platforms I'm familiar with it is passed as the first argument, but I don't do a lot of C++ coding, so I'm not sure if this is guaranteed by the standard. You can always disassemble some C++ code on your platform to confirm.
The C++ symbol naming is rather more painful than in C, and varies from compiler to compiler. I suppose you could figure out the right symbol name to use by disassembling a compiled function definition, just make sure that: the function is a member of the right class, and has the right number and type of arguments.
Unless you really need to reproduce a C++ function in situ, I would probably just make a standard C function and do the usual extern "C" { ... } around its declaration.
Does your compiler have an inline assembly syntax? If you have that, it may be the easiest option, and you can let the compiler handle the function naming and call syntax pieces.
Alternately, Stephen's suggestion of writing the C++ method as an inlined wrapper around a "simple" C function call is a good one. (You probably want to make it just a plain function, not a static member function as in your post, to get a simple C interface to it.)
I would find the compiler-dependent flag and write the assembly within the C++ function. Usually there are ways to reference local variables from within the assembly section.