简体   繁体   中英

How can I get information about a caller of a function in C?

I have a function, void funct (struct *B) . It will be called by some instances of struct A . It only takes a pointer to strut B and modify that struct B instance. If struct A has char *name . My question is, can I get access to the A_instance->name ? in the funct ? If yes, how? Thank you

You say this is C, which leaves out member functions (C does not have member functions, classes, etc). That means that funct is just a function (not a member of something) and that therefore, you only have the information that is passed in, and the globals. Since neither of those things contain what you want, you can't get it.

However, you also say that funct is called by 'some instances of struct A'. This doesn't make any sense, because in C structures don't have member functions, and thus can't make calls. Either you mean that operations on some instances of struct A are calling funct (in which case, my first answer applies), or you really are working with C++, and you've got member functions in struct A.

If funct is a member function of struct A, then funct has full access to all the members of the instance of A that called it, and can therefore check 'name' directly. Otherwise, we're back to my first answer.

In order to fix this, you're either going to need funct to be a member function of struct A (thereby going to C++), or you're going to need to pass the relevant information into funct.

It sounds like you're trying to write a function which needs to process a name value which is present in 2 different structures: struct A and struct A . If that's the case then why not take a char* directly in funct and have callers pass the appropriate name field?

funct(char * name) { 
  ..
}

funct(aInstance->name);
funct(bInstance->name);

I'm afraid C doesn't permit you access to the calling functions data. The easiest would be just to pass in a pointer to "struct A", at least then you'll always have access to A.

void func(struct B* b_ptr, struct A* a_ptr) 
{
    /* ... */
    /* do whatever you like with a_ptr->name */

}

Assuming you have a program like that:

struct B {
  int dummy;
}

struct A {
  char *name;
  struct B* b;
}

void funcA ( struct A* a ) {
   funcB ( a->b );
}

void funcB ( struct B* b ) {
   /* do something */
}

and you want to find out something about a in funcB , there is no proper way to do it. What you might try to do is, by using pointer arithmetic or negative array indices, to guess the location of a on the stack, which might even work with a given compiler on a given platform. If you make it work that way, please don't forget to post the solution to The Daily WTF .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM