How can I check a function was called by another function? - c++

I am currently trying to make sure that a member function of one class is only called by a member function of another class.
The architecture is imposed and cannot be changed, the port means that some logic has to be done in a.call() before calling b.call(). a.call() therefore calls b.call() to simplify things and make sure the order is respected.
I found this answer to my question. Only, the problem is that I am using classes, and the two classes have the same member function name and so the #define tries to replace all the occurrences which have different prototypes.

I recommend the passkey pattern. It's very good for giving fine grained control on who can do what with your function.

Off the top of my head, options would be:
Make b.call private and make b add a or a.call as a friend
Turn b.call into a class and put the body into a a private constructor with a or a.call as a friend
grep the source code for b.call, make sure the only call is in a.call, and add a comment at the declaration saying "if you call this function you will be fired"
Change b.call to take at least one of the values it needs as a parameter (even if it ignores it and uses the value from somewhere else)

Can you change b.call to take a reference to a? This way, b.call can call a.call itself:
struct A {
void call() {
// do stuff
}
};
struct B {
void call(A & a) {
a.call();
// do stuff
}
};
This makes sure that a.call is always called before the rest of b.call is executed.

How about using a flag?
a.call()
{
// ...
flag = 1;
b.call();
flag = 0;
}
b.call()
{
if (flag == 0)
return;
// ...
}

If you program for certain platform (say x86 or x64), and you know the calling convention (e.g. cdecl), then you can get this info from the stack
Say you want to check the object that called the function, so use the this pointer that is pushed to the stack prior to calling the member function: get the this pointer and compare it with the object that you want (this_pointer == a)
If you want to check certain function, get the caller address from the stack and check against that function: caller_address == A::call. If it's a virtual function, use the this pointer to get the vtable.
Depending on the calling-convention and the order of pushing variables on the stack, you may have to check first the input variables sizes, in order to get to the information you need.

Related

Replace lambda function with polymorphic member function

I have the following member in a polymorphic class Parent and I am looking for a way to replace foo by some kind of virtual member bar:
void Parent::myFunc() {
// lots of variables
// complicated calculations
while (/* loop condition */) {
// more variables and calculations
auto foo = [&](int n) {/* ... */};
foo(42);
// want to replace with virtual
// bar(42);
}
}
The problem I am having is that foo captures everything, and I do not know that correct way to grant bar the same access.
Passing everything to bar as parameters would lead to a big parameter list, and does not seem to be an elegant solution
I can also turn local variables of myFunc() into members of Parent, but this would needlessly extend the life times of those variables, especially for the loop variables.
You’re right to not want to make the locals into members—which would, among other things, lose thread-compatibility. Since overriding functions can be defined in other translation units, you have to define some sort of interface and call it.
If you want to avoid a long parameter list, gang the arguments into a struct (which might be a protected member type of the base class). If appropriate, you can even reuse the struct object for each iteration and just update the relevant fields, or make them be references to the appropriate local variables.
You can also, if it works for your derived classes, define several virtual functions to be called with subsets of your currently-captured variables.
In either case, these emulations of capturing would be called from within the real lambda used for whatever purpose (e.g., a callback as mentioned in the comments).

How to use a C++ lambda to convert a member function pointer to a normal function pointer for use as a callback

I have some code that needs a C function, but I want to instantiate a bunch of class instances and pass a member function from that class as the C function. I need to capture N instances concurrently. I'm hoping I can do it as a lambda.
Here's what the resulting function should look like (roughly):
// This is the code I want to interface with:
typedef void func(ParamClass param); // ParamClass is NOT my class
extern void notMyCode1(func funcArg); // Code I want to call, saves funcArg
extern void notMyCode2() // uses saved funcArgs
// Here is the type of class I want to instantiate:
class MyClass {
public:
MyClass(int arg) : saveArg(arg) {}
int saveArg;
void myFunc(ParamClass param) {
// uses saveArg and param to do the right action
}
};
void useCase(void) {
for (int i = 0; i < max; ++i) {
MyClass myInstance(Myclass(i)); // maybe need vector to hold these?
notMyCode1(myInstance.myFunc); // this code is what I don't know how to write
}
notMyCode2();
}
Background. The library I want to call is Google Benchmark. notMyCode1 is their benchmark registration function. notMyCode2 runs the benchmarks that were registered. ParamClass is data their code passes into the benchmark.
Now, normally, one passes a simple C function to the registration code, one for each benchmark one wishes to run. However, I want to run the same code over and over again parameterizing it by this number "i" and have each "i" treated as a separate benchmark. So, I want to capture "i" in a class (or via a lambda, but something that yields me multiple
C function pointers with the value of "i" bound in each one). I tried making "i" a parameter to the benchmark and passing it in, but then the benchmark code treated "i" as something to sum over (and I want each "i" treated as a unique benchmark with a different parameter for the statistics to be calculated over).
This seems like something that ought to be simple to do, (it's just a closure) but I'm not that conversant with function pointers (or C++ lambdas). If it were my code, I would just pass the class instance in, but it isn't.
I've seen examples that use static functions in the class, but I specifically want to capture the value of "i" and get multiple function pointers, each one capturing a different value of "i".
You cannot.
A lambda only has a conversion to function pointer if it is stateless (i.e. there's no captures). To call a member function from a lambda, you need a pointer to an object with which to call the member function. This is captured, rendering the lambda object not convertible to a simple function pointer.
The only option you might have is to do the index parametrization at compile time using templates. Then you return to using simple static functions of a class template which can be passed as a C callback.

Passing a member function of a class to a parameter outside the class

How do you pass a member function of a class as a parameter to another member function of another class?
class theSecondClass
{
public:
void theFunctionReceiver(void (theFirstClass::*Function)(void));
{
// This part is wrong. "Operand of * must be a pointer"
(*Function)();
}
}
class theFirstClass
{
public:
theSecondClass * SecondClassInstance;
void theFunctiontoPass(void)
{
printf("It worked \n");
return;
}
void theFunctiontoCall(void)
{
SecondClassInstance->theFunctionReceiver(theFunctiontoPass);
}
};
Take the assumption that theSecondClass and theFirstClass are both made already. I'm calling theFirstClass->theFunctiontoCall() from somewhere.
I don't get it. When I pass it in, isn't it pass in as a pointer?
I've taken a look at several similar threads around, but I don't understand them fully.
I'm using VS 2013, basic compiler.
When you write this statement:
SecondClassInstance->theFunctionReceiver(theFunctiontoPass);
What you presumably meant was:
SecondClassInstance->theFunctionReceiver(&theFunctiontoPass);
Which should give you a compiler warning that it's an unqualified member reference, which would point out to you that what you are actually writing is:
SecondClassInstance->theFunctionReceiver(&theFirstClass::theFunctiontoPass);
You are getting a pointer to a member function on the class definition. The "this" is not implicit or included in the package. The only way you're going to be able to call it without a class instance is if it is static. (In which case it won't type-check as a member function...it will just be an ordinary function pointer.)
If I'm going to pass in a reference to my class, why would I even need to pass it the function? Couldn't I just call it with, in the case of the link, ButtonObj->Buttonfunc();
The only reason you would use pointers to member functions is to get some kind of abstraction, where one piece of code can call a member function it doesn't need to explicitly name. If you're okay with theSecondClass::theFunctionReceiver knowing the name of theFirstClass::theFunctionToPass and the identity of theFirstClass...then sure, just pass a reference to an instance of theFirstClass and call the method explicitly.
You might want a situation where theSecondClass is going to call any one of a number of member functions on theFirstClass with matching signatures...it just doesn't want to hard-code which one. In that case, then passing a pair of a class reference and a member function can be done. You seem to suspect this doesn't come up too often as useful, and you would be right. Every year I have to go back and look up the syntax for how to call pointers-to-members on a class, because it almost never comes up except in StackOverflow questions:
How to call through a member function pointer?
More likely what you want (and what people asking those SO questions actually want) is to separate concerns so that theSecondClass has a hook to execute something, but doesn't need to know about theFirstClass at all. Look into lambdas, std::function, and std::bind for generalized solutions which you may be able to experiment with to your satisfaction.
Here is an example to show you what that would look like to conveniently wrap up the call abstractly into a std::function. It makes a function object on the spot, that captures the enclosing this pointer so that when it is invoked it calls the method on the object:
#include <iostream>
#include <functional>
class theSecondClass {
public:
void theFunctionReceiver(std::function<void()> const & Function) {
Function();
}
};
class theFirstClass {
private:
theSecondClass * SecondClassInstance;
public:
void theFunctiontoPass() {
std::cout << "It worked\n";
}
void theFirstClass::theFunctiontoCall() {
SecondClassInstance->theFunctionReceiver(
[this]() {theFunctiontoPass();}
);
}
};
int main() {
theFirstClass tfc;
tfc.theFunctiontoCall();
}
Note this is C++11, which I suggest using if you're not already. Less convenient notations and mechanisms exist in C++98, though.
This corrects problems with your code that go beyond the issue you mention. Please review writing a Minimal, Complete, Verifiable Example. It should be possible to paste your provided code into a compiler and see only the error you wish to discuss.
This adds semicolons after the ends of class definitions
This removes the semicolon after method declarations when you are supplying bodies in the class
You needed various forward definitions to get it to work as you had it, this doesn't require them
When a function takes no parameters, it's customary to define as void foo() not void foo(void). return; as the last line of a function returning no value is kind of superfluous as well.
Avoid writing new C++ code using printf, learn iostreams
Bias member variables to being private or protected.
On StackOverflow code samples try and keep them short and not need scroll bars; it's best to not give opening braces their own line (most of the time)
While naming is subjective, I'd suggest that giving your class names initial caps is a better idea than giving variables initial caps.

Pass a non-static method pointer as an argument to another method

Sorry to ask such a question as I'm sure it's been answered before, but I'm struggling to find an answer and it's not for the want of looking... anyway..
class foo
{
void read(void (*func)(obj&))
{
// many things happen to obj...
(*func)(obj); // Calls the function pointer to the handler.
}
};
class bar : public foo
{
void handler(obj&)
{
//
}
};
void main()
{
foo f;
typedef void (foo::*funcptr)(obj&);
funcptr ptr = &foo::handler;
f.read(ptr); ????
}
So basically, all I'm trying to do is pass the non-static member method called handler as a function pointer to the read method, so that when the callback is executed, the handler is called.
I've tried all sorts of ways to make this work and don't want to make static methods (for reasons I won't go into). I think I'm pretty close, but have sort of fallen over right at the end! Any help would be appreciated.
You cannot do that: unlike static functions that can be called on their own, the call of a member function requires knowledge of two things - the function being called, and the object on which to call it. That is why it is not possible to pass a member function to an API expecting a "plain" function pointer.
If you do not have access to the source of the foo class, you can create a static function that calls a member function on an object stored at a well-known location (i.e. in a static variable). If you do, consider changing the API to take a function object, similar to what functions from the standard C++ library do.
Finally, there is a common approach used in C libraries that take function pointers - passing an additional void* pointer, which will be passed back in a call to your function pointer; pthreads library does that. If this is the case, you can create a struct that wraps the invocation target object, and pass a pointer to this struct to be passed back to your static function.
AFAIK I don't think there is any other way. You will have to make the method static.

How to find out if a global variable has changed in c++?

I have a silly question! Let's suppose you have a global variable that is used all over the project and you are going to do something when it changes ,for example calling a function .
One simple way is to call your function after every change. But what if this global variable is part of a library and will be used outside .Is there any better solution ?
Presumably you want to find when your variable is modified without tracking down ever reference to it and rewriting all that code that depends on it.
To do that, change your variable from whatever it is now to a class type that overloads operator=, and prints/logs/whatever the change when it happens. For example, let's assume you currently have:
int global;
and want to know when changes are made to global:
class logger {
int value;
public:
logger &operator=(int v) { log(v); value= v; return *this; }
// may need the following, if your code uses `+=`, `-=`. May also need to
// add `*=`, `/=`, etc., if they're used.
logger &operator+=(int v) { log(value+v); value += v; return *this; }
logger &operator-=(int v) { log(value-v); value -= v; return *this; }
// ...
// You'll definitely also need:
operator int() { return value; }
};
and replace the int global; with logger global; to get a log of all the changes to global.
I'd say the easiest way is to create a set method for your variable that calls the function and let it be public, while the variable itself remains private:
//public
void setYourVariable(int newValue)
{
YourVariable = newValue;
YourFunction();
}
//private
int YourVariable;
You need to make an accessor function to set your global variable. Then you can call your special function from that accessor instead of requiring all of the callers to do it themselves.
Just to answer the actual question: No, there isn't a way to determine "when a variable changes" in C++. Technically, if you have enough privilege and the hardware supports it, you could set a "breakpoint on write" for the address of your variable. But it's just a very roundabout way to achieve something that is EASILY achieved by renaming the variable, and then fix all the places where the variable is being accessed to call a function to update the value, and if appropriate also call a function at the same time - as suggested in several answers.
Since u are saying it may get called from out side also, as Kevin said it is good to have Get() and Set(...) methods . Mainly 2 advantages.
1) Through the set u can call a function or do action whenever value changes.
2) You can avoid directly exposing your variable to the outside directly.