How to get the caller of a fuction?
-
at run time i want to known a fuction's caller ,how can? for example: void a(int i) { CString szCaller = GetTheCaller(); MessageBox(szCaller); } void b(int j) { a(j); } I'd like to get a message :"void b(int j)" How to implement method "GetTheCaller()" Scratch
-
at run time i want to known a fuction's caller ,how can? for example: void a(int i) { CString szCaller = GetTheCaller(); MessageBox(szCaller); } void b(int j) { a(j); } I'd like to get a message :"void b(int j)" How to implement method "GetTheCaller()" Scratch
-
at run time i want to known a fuction's caller ,how can? for example: void a(int i) { CString szCaller = GetTheCaller(); MessageBox(szCaller); } void b(int j) { a(j); } I'd like to get a message :"void b(int j)" How to implement method "GetTheCaller()" Scratch
You want a stack trace, huh? I did it once and regreted it. It was a great bunch of work. Some starting points: 1. Look at the StackWalk Win32 API function. Walk the stack until you find the calling function. 2. Once with the address of the calling function, you'll need the SymFromAddr Win32 API function. 3. You'll need to ship the PDB file together with your application, because the Symbol functions will need this file. If you only need this info for debugging purposes, you could try looking, IIRC, the address
(&i)[1]
(the address of the first parameter + 4 bytes. In your case, the parameter is an int), which will give you the return address on the stack. This is a hack and can fail for a hundred reasons, including the automatic inline made by the optimizer. The right way of doing it is the StackWalk way. I see dumb people -
How 'bout just passing the caller as a string argument? Getting the calling function's name as a string is way beyond my knowledge ;)
-
at run time i want to known a fuction's caller ,how can? for example: void a(int i) { CString szCaller = GetTheCaller(); MessageBox(szCaller); } void b(int j) { a(j); } I'd like to get a message :"void b(int j)" How to implement method "GetTheCaller()" Scratch
How about creating a global array of some appropriate size, adding a call in every function in your code to add its own name to the array, and then at any point, just get the last so-many elements to know where you came from? It's not really a call "stack" as much as a call "trace." The caller of any function would be the last element in the array. The function to add to the array would have to do all the proper subscript incrementing and roll-around, making it a circular list of the last some-number of functions called. This may not be appropriate, because you do have to add something to every function. Dave "You can say that again." -- Dept. of Redundancy Dept.