Address of a public function from a C++ class - c++

My application needs parts of a C++ code to be called from a C program.
The problem arises when i have to obtain the address of a public function.
I do not know how to get the address of a public function from a class.
I specifically need the address so that i can pass the address as a function pointer.
Any other solutions to circumvent the solution are also welcome.
I have tried static casting but it has not worked.
static_cast<izot_events*>(thisizot_events)->myIzotWink()
This calls the function but i am interested in the address.
I have tried using
static_cast<izot_events*>(thisizot_events)->myIzotWink
But this returns an error.
Here is also some code for reference.
void* C_Create() { return new izot_events(); }
thisizot_events = C_Create();
static_cast<izot_events*>(thisizot_events)->myIzotWink // This does not work i.e I cant get the value.
static_cast<izot_events*>(thisizot_events)->myIzotWink() // While this gets called

Make the function static, then you can do &MyClass::my_function. You should not do any casting; instead make your static function have the right declaration to match the function pointer's type.

Related

Use function-pointer as proxy to member-function

Assume a class like this:
class Speaker {
public:
void (*saySomething)();
}
The point is that we can instantiate that class and call the stored function pointer in order to make it say something (whatever that turns out to be). The background to such an approach is to have the actual function reside in a shared library and Speaker acts as some sort of wrapper class (The function gets resolved in the library and the pointer is assigned to the variable in the class).
Now consider we have another class that extends Speaker:
class ConstantSpeaker : public Speaker {
protected:
std::string message;
void doSpeak();
}
with the method's implementation like this:
ConstantSpeaker::doSpeak() {
std::cout << message << std:endl;
}
Now I want to assign the saySomething pointer in a way so that the call is somehow re-routed to ConstantSpeaker::doSpeak(). This however isn't possible directly as doSpeak() is a member function and saySomething is a pointer to a non-member-function.
Another idea I had was to create doSpeak() as a friend-function of ConstantSpeaker instead. Then the pointer-assignment works fine but now doSpeak() would require the object holding the actual message as an argument in order to be able to access the message.
To me it seems as if there should be a (more or less) straight-forward way of doing this given that I can only ever call Speaker::saySomething when having an instance of a Speaker at hand. Therefore the availability of the corresponding object shouldn't be a problem but still I can't figure out how I have to assign that pointer.
The only solution I could come up with is to add a public virtual Speaker::doSaySomething function whose implementation will call the function pointer (which is then no longer public in order to prevent miss-usage) and that can be overwritten by ConstantSpeaker to call ConstantSpeaker::doSpeak() instead.
Is there another solution to this problem?
Another solution is just to use a standard std::function<void()>, and then it can be still declared as public.
Also, instead of bare function pointer, you can use pointer to member function, but be aware about slicing, when using it inside a base class.
But, I think, the most trivial way of doing this is just by using virtual function, like you've mentioned.
Maybe tell more about your context? What is the problem you are going to solve?

Unexpected behavior when passing pointer to private variable

Currently I am working a lot with GUI design where I am using a lot of callback methods. In general those methods looks like: static void* Foo(void* data). Thanks to them I found out that I can access private variables without any issue just by passing their pointers.
Let say I have class like this:
class MyClass
{
public:
MyClass();
static void* Foo(void* data);
private:
int dummy_data = 3;
}
and methods:
MyClass::MyClass()
{
Foo((void*)&dummy_data);
}
void* MyClass::Foo(void* data)
{
received_value = (int*)data;
printf("Private value: %d\n",received_value);
}
And I can read dumy_data value. Normally if I would try to access this value compiler will rise error flag saying that this is private variable. And it doesn't matter if I'll pass it as a value, or pass pointer to my class and try to access this way.
So my question is - why is that happening? Yes, I know that I am passing pointer to value, but shouldn't compiler rise flag here as well?
The private and public sections control visibility of the names declared in those sections. They don't control visibility of the data. Outside code cannot refer to the MyClass::dummy_data name because it's private. If the class chooses to expose the value of that variable somehow, or even the address, then that's the class's choice, and any code with access to that other avenue (a pointer, in this case) is free to read it. There is no language error present, so the compiler doesn't complain.
It's valid.
Access restrictions are emplaced on the names of the members, not the members themselves. (Otherwise many getters would not work!)
A function that has been permitted (by being a member function) to access that member by name, has decided to pass along a pointer to that object. If you don't want that to happen, don't do it.
It would not actually be possible, in the general case, for the compiler to detect and block this code even if it were supposed to.

Class member function cannot call another member function of same class?

I'm writing a private member function for a class (function1) and for a chunk of the code I decided it'd be easier to put that chunk into it's own function (function2) , and call it from function1. However, the compiler is saying that function2 needs an object. This doesn't make sense to me, because an object has to be created in order for function1 to work, so the object for function2 seems like it should just be "this".
int ClassName::function1(args)
{
//some code;
//some code;
function2(args); //says I need an object to call the function here
//some code;
}
int ClassName::function2(args)
{
//some code;
}
The exact error code is "A nonstatic member reference must be relative to a specific object". I've been searching for hours and every instance of this comes from someone calling a class member function from outside of the class without using a object pointer. I cannot find anything for a class member function calling another class member function. I also thought I had called member functions from other member functions in the past without trouble, so I'm super confused. I could just delete function2 and do all calculations inside function2, but then I wouldn't learn anything!
I tried switching the order of the function definitions in the cpp file. The order of the prototypes in the header. Changed function2 from private to public. No dice. I've exhausted google, my own programming knowledge, and any experimentation that I could think of, so I have to ask you guys for help now. If you need extra info, let me know, although it seems like the exact code inside my functions would be irrelevant as far as the problem goes.

How to get a "simple" function pointer from a member function

I'm having a problem with function pointers and nothing I found on the net helped me to solve this problem.
I have a function from a C API which take a pointer of a void function :
extern int APIFunction(int, void (*func)(int));
I have a class with the function I would like to put when I call the API function.
class MyClass
{
public:
void myFunction(int status, otherAPi arguments...);
};
Then, I created a pointer to my member function and created a new instance of my class
typedef void (MyClass::*MyClassFunctionPointer)(int stat, otherAPi arguments...);
MyClassFunctionPointer fctPointer= &MyClass::myFunction;
LicenseSecurity instance;
I get an error when I try to call my APi function with the function pointer I created:
int stat = APIFunction(5, fctPointer ); // -> error 1
int stat = APIFunction(5, instance.*fctPointer ); // -> error 2
I got errors respectively in the first and second case:
E2034 Impossible to convert 'void (MyClass::*)(int, otherAPITypes...)' into 'void (*) (int, otherAPITypes...)'
E2342 Bad type correspondence in the parameter 'func' ('void (*)(int, otherAPITypes...)' desired, 'void(int, otherAPITypes...)' obtained)
I don't have access to the API function so I can't modify it. To summary the problem: how How to get a "simple" C function pointer to put in argument of a function from a member function of my class?
Thanks
Unfortunately, you can't. Sorry.
Ideally, your API would accept something like std::function that would allow you to wrap free functions or member functions. But if you can't modify the API, then you have no choice but to provide a free function.
You can't get a "simple" function pointer to a non-static member function because the function requires a this pointer when called. If you were to create a function pointer like that then when the function was called there would be no this pointer for it to reference.
With an ancient C API like that, you unfortunately don't have any way to do this.
What you have to do is make a static or non-member function to take the callback, and then figure out which instance of the object to call the member on. Some C APIs allow a user data to be passed to the callback, and in that case you use that to store the this pointer in question. If that's not an option you can use a global or singleton object and only allow a single such callback to be registered.
You can declare the callback as either a standalone function or as a static method of the class. The tricky part is accessing a class instance pointer inside the callback.
Ideally, a well-designed API allows you to specify a user-defined value to callbacks. That allows you to easily pass in a class instance and access it directly inside the callback. But it sounds like you are not working with such an API, so you need to use a workaround.
If you have only 1 class instance being used with the API at a time, you can store the instance pointer into a global variable, and have the callback use the global variable to access the instance.
But if you have multiple class instances being used at the same time, you are looking for a thunking solution, similar to the VCL's MakeObjectInstance() function, which allows TWndMethod-signatured class methods to be used as Win32 window procedure callbacks. Essentially, a block of executable memory is dynamically allocated, stub assembler code is written into the block, and the instance pointer and class method pointer are stored in the block as well. The block is then passed to the API as if it were a function pointer. When the API calls the "function", the stub code gets executed, which has to manipulate the call stack and CPU registers to call the stored class method pointer passing the stored instance pointer as its hidden this parameter, while preserving the semantics of other parameters, the call stack, function result, etc.
Nothing in C++ really accomplishes that kind of thunking natively. It is not difficult to implement manually, but it is not trivial either (have a look at the source code for MakeObjectInstance() in the VCL's Classes.pas source file). The hardest part is coming up with the necessary stub code that matches the semantics of your particular class method's signature.

how can I use a non static instance in a static method in c++?

I have a an instance of lasse1 and I want to use it in a method of lasse2 , this method is static method, this just doesn't work :
class Lasse2{
......
public :
static void function(void);
Lasse1* obj;
........
};
And now i want to use it like :
void Lasse2::function(void){
obj->dosmt(); // this doesn't work
.........
any idea how can I solve this?
If you want to access an instance member of your class, then you must have an instance of that class. There's no way around this. Your options are:
Make obj a static member. Do this if you intend to have a single obj for all instances of this class.
Remove static from function() so it becomes an instance method.
If you can't do either of those, then you need to find a way to pass an instance pointer to your function. For example, APIs that require a function pointer often have a mechanism for passing pointer-sized data to that function when it's eventually called.
Change your static method to explicitly pass the object pointer:
static void function(Lasse1* obj)
{
obj->dosmt();
}
But before you do, consider what you're really trying to do (and even write another question if you like).
You need an instance of your class to pull that off.
Create one or receive it through other means (function argument, global variable, class static variable, etc)
SLaks said it best: "You can't"
Here's why:
When you declare a member variable (not static, see obj above), you're telling the compiler that each object of type Lassie2 contains a pointer to a Lassie1.
When you declare a method static, that means that it is independent of all the instances (the actual objects) of that class. It doesn't operate on an object.
So inside of Lasse2::function, there's no this, no Lassie2 object for you to get the obj pointer from.