Converting class function pointer to void* or vice versa - c++

Im trying to compare the address of two functions for equality. Type of my stored function is known. This system normally works, consider the following code (written as sample not from the program):
virtual bool compare(void *fn2) {
void (*fn)(int);
if(fn==fn2)
return true;
}
However when class functions came into consideration the same method doesn't work.
virtual bool compare(void *fn2) {
void(__thiscall myclass::*fn)(int);
void *fn2;
if(fn==fn2) //error C2440 type cast: cannot convert void* to void(__thiscall...
return true;
}
These functions override a common base class' pure virtual function similar to following:
virtual bool compare(void*) = 0;
Since I cannot use template<> in virtual functions I am out of options. Is there a way (anyway) to unify class functions and regular functions?
Thanks in advance,
Cem

Posix requires the ability to convert function pointers to void*. Standard C++ does not support it.
Member function pointers are not pointers in the ordinary sense, they're more like offsets (even for a non-virtual member function).
Both implementations you show for compare would have Undefined Behavior even if the comparisions and casts were valid, because they fail to return anything in the case where the pointers don't compare equal. Instead of if(blah == bag){ return true; } just do return (blah == bah);.
The problems stem from casting away necessary type information. That's generally not a good idea. Why are you casting away the type information that you need?
Solution: (1) don't cast away necessary type information, and (2) redesign to get rid of that compare function. Also take note of Roger Pate's comment that it seems you're asking about a particular attempted solution rather then the problem. What is the problem?
Cheers & hth.,

This doesn't work because member function pointers are not actually convertible to regular pointers- their size is undefined. In some implementations of some class hierarchies, the member function pointer can be five times the size of a regular pointer. How is this going to work with a comparison to void*?

Related

Passing pointer to struct, vs. passing void pointer and casting to struct

I'm working on a legacy code base that has this pattern:
struct sometype_t { /* ... */ };
int some_method(void *arg1) { // void pointer
((sometype_t*)arg1)->prop1; // cast
}
Is there any (common) scenario where it would be unsafe to use sometype_t * instead of void *?
int some_method(sometype_t *arg1) {
arg1->prop1;
}
The pointer isn't passed across ABIs or into 3rd-party libraries; it stays entirely within C++ code that we own.
It's usually not a good choice, but the only situation I'm aware of where this really make sense is if you want to have stateful callbacks passed into a function, without using templates:
void takes_callback(void(*f)(void*), void * data);
Basically the gist is that since you aren't using templates, you have to fix the function signature you accept (of course, it can and often does take other arguments and return something as well). If you just call the function with your own parameters though, the function can only hold state between calls via global variables. So instead the contract for takes_callback promises to call f with data as a parameter.
So, if you wanted to use some_method as a callback in such an API, you would have to have it take void*, and do the cast internally. Obviously, you are throwing away type safety here, and if you happen to call takes_callback with &somemethod and a pointer to anything that's not a sometype_t you have UB.
Having a C ABI is one reason to avoid templates, but it's not the only one. Maybe they were worried about code bloat, or wanted to keep the implementation in a .so so that versions could be upgraded without recompiling, etc.
The obvious common scenario that immediately comes to mind is callbacks for some functions from C standard library.
For example, the proper way to write the comparison callback for std::qsort is to declare the function with two const void * arguments and then cast them to proper specific pointer types inside the callback.
Replacing these const void * parameters with specifically-typed pointers will simply prevent the code from compiling.

The reason behind strict rule of passing an array by pointer to a function in C++ standard

In C++ the only way to pass an array to a function is by pointer, considering following
functions:
void someFunc(sample input[7]){
//whatever
}
void someFunc(sample input[]){
//whatever
}
void someFunc(sample (& input)[7]){
//whatever
}
All above function parameters are identical with following function parameter when the function is not inlined:
void someFunc(sample * input){
//whatever
}
Now to pass the array with value we have to put it in a structure like below:
struct SampleArray{
public:
sample sampleArray[7];
};
Now I'd like to know if anyone knows the reason behind this design in C++ standard that makes passing pure arrays by value impossible by any syntax and forces to use structs.
Backward compatibility reasons. C++ had no choice but to inherit this behavior from C.
This answer to the earlier similar question addresses the reasons why such behavior was introduced in C (or, more specifically, why arrays and arrays within structs are handled differently by the language).
C++ adopted that part of C, but added the ability to pass arrays by reference (note that your third version of someFunc passes the array by reference, and is not equivalent to using a pointer to its first element). In addition, C++ includes various container types that can be passed by value (recently including std::array)
Probably as a function of its C ancestry. Arrays being just pointers to memory it'd be kind of hard for that to be done transparently without generating extra code by the compiler. Also it's trivial to implement a container class that does lazy copy on write, which will perform better.

Is it possible to declare void pointer to a template function in C++?

Is it possible?
If as I have understood is correct, void pointer can point to any type. Therefore, a template function (undeclared type) is possible? or void pointer is only reserve for "variable" not function? Then what about void function pointer?
You can cast any function pointer type to any other, but you'd better cast it to the right type before you call it. You can therefore use void(*)() as an equivalent to void* for function pointers. This also works with function templates.
template<typename T>
void f(T){}
typedef void(*voidfp)();
voidfp fp=static_cast<voidfp>(&f<int>); // store address of f(int) in variable
static_cast<void(*)(int)>(fp)(3); // call the function
fp=static_cast<voidfp>(&f<std::string>); // store address of f(std::string) in variable
static_cast<void(*)(std::string)>(fp)("hello"); // call the function
According to the Standard, a void* is not required to be able to hold a function pointer. (It is required to hold a pointer to any kind of data). However, most cpu architectures you're likely to see these days have data pointers & function pointers that are the same size.
There is an issue here, because of the words used I am afraid.
There is a difference between pointers and function pointers, most notably they need not be the same size.
Therefore it is undefined behavior to use void* type to hold the address of a function pointer.
In general it is not a good idea in C++ to use void*. Those are necessary in C because of the lack of a proper type system but C++ type system is much more evolved (even though not as evolved as recent languages).
You could probably benefit from some objectification here. If you make your method an instance of a class (template) you can have this class derived from a common base class. This is quite common, those objects are called Functors.
However, without a precise description of your issue, it'll be hard to help more.
to do this with templates you need some trickery, else the compiler cannot disambiguate the function (this is really not recommended, its horrible to read, and probably violates a few thousand porgamming best practices)
IE: this does not work (atleast under VS08 & GCC 3.5):
template <typename tType> tType* GetNULLType()
{
return static_cast<tType*>(0);
}
void* pf = static_cast<void*>(GetNULLType<int>);
you instead need to do:
template <typename tType> tType* GetNULLType()
{
return static_cast<tType*>(0);
}
typedef int* (*t_pointer)();
t_pointer pfGetNull = GetNULLType<int>;
void* pfVoid = (void*)(pfGetNull);
(and before purists moan, it seems C++ style 'safe' casting will not allow this)

Call a member function with bare function pointer

What's the best way to call a member function if you have an object and a bare function pointer pointing to the member? Essentially I want to call the function pointer with thiscall calling convention.
Background: I'm looking up symbols in a shared library dynamically, obtaining a factory function pointer and a pointer to a certain member function I want to call. The member function itself is not virtual. I have no control over the shared library, I just have the binary.
Example:
typedef void * (*GenericFptr)();
GenericFptr lookup(const char *);
class CFoo;
GenericFptr factoryfn(lookup("CFoo factory function"));
CFoo *foo = reinterpret_cast<CFoo *>(factoryfn());
GenericFptr memberfn(lookup("CFoo member function"));
// now invoke memberfn on foo
Currently I'm using an union to convert the function pointer to a pointer to member function. It's ugly and creates dependencies to compiler implementation details:
class CFoo {
public:
void *dummy() { return 0; }
};
typedef void * (CFoo::*FooMemberPtr)();
union {
struct {
// compiler-specific layout for pointer-to-member
void *x, *y;
GenericFptr ptr;
} fnptr;
FooMemberPtr memberfn;
} f;
f.memberfn = &CFoo::dummy; // init pointer-to-member
f.fnptr.ptr = memberfn; // rewrite pointer
void *result = (foo->*f.memberfn)();
A pointer to member function can't be stored in a pointer to function because it needs more information (for instance in case of multiple inheritance an offset may have to be applied to this before the call). So you can't do without knowledge of implementation details.
If you want to be portable, the easiest is for your library to provide wrapper functions doing the member call.
Unfortunately a member function pointer has more information than a standard function pointer, and when you get the standard function pointer, converting it to a member function pointer would effectively be trying to generate extra data out of thin air.
I don't think there's any portable way to do what you're attempting, although if the union appears to work you could probably get away with that. Again, you would need to know the representation and calling convention for these methods for each compiler you wish to use to build the bode.
If you know the member function's name, why can't you just do foo->dummy() for example? Otherwise either the lookup function needs to provide a full member function pointer or the library would have to provided a C wrapper interface with normal functions to which a this pointer can be passed.
The following two links provide insight and possibly a solution. Note that calling a member function pointer with a this argument usually don't work, since you must take into account virtual methods, multiple and virtual inheritance.
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
http://www.codeproject.com/KB/cpp/ImpossiblyFastCppDelegate.aspx
According to the answer below it is doable in GCC, but not portable:
https://stackoverflow.com/a/5067992/705086

Member function still const if it calls functions that break "constness"?

I'm wondering if a class's member function should be const if it calls other functions that modify its data members. A good example would be a public member function that uses private member functions to do the brunt of the work.
void Foo::Show() const { // Doesn't directly modify data members in this function
ShowPig(); // One or all of these functions modify data members
ShowCow();
ShowBar();
}
Maybe not the best example, but you get the idea.
Any Good compiler does not allow this. You should get the compiler error.
The compiler should not allow you to do that. Example below.
//MS VC 2008
class Foo
{
int m_iBar;
void ThisIsConstFunc() const
{
m_iBar = 9; //error C2166: l-value specifies const object
ThisIsNonConst(); //error C2662: 'Foo::ThisIsNonConst' : cannot convert 'this' pointer from 'const Foo' to 'Foo &'
}
void ThisIsNonConst()
{
m_iBar = 9;
}
};
If a function calls functions that modify certain data, then it should be said that the function itself modifies data. It just happens to be abstracted.
So no, that function should not be const.
C++ provides the mutable keyword for the rare case that you actually want to allow this. And there are times where it happens, for instance if your function does not change the logical state of the object, but may modify one or more members of the object.
These cases are very rare. In the vast majority of cases you should mark the member function const if neither that function nor any function it calls modifies the state of the object.
Yes, the compiler won't let you, as pointed out. Of course you can do it anyway but if the function needs to be const usually it's a bad idea. If it doesn't need to be const, don't just put it in there for no reason. There's really not much benefit to const and many potential serious problems, you just get forced into it at times.