3 ms·
Ask HN: Work Around for passing C Pointers
hey, I'm wondering if there's a way to get the ptr to a caller of a function from within the called function in c (without passing in the ptr as an arg). Basically, I've been experimenting on how to do oop style programming in c, so any ideas or suggestions here are more than welcome :) Here's an example to help clear things up.
struct Person {
char name[32];
char * (*setName)( struct Person *, const char *);
};
char *setName( struct Person *self, const char *name) {
strcpy(self->name, name );
}
int main(void) {
struct Person *p = (struct Person *)malloc(sizeof(struct Person));
p->setName = &setName;
// here I'd really like to not have to pass the ptr 'p'
// is there any way to do this?
p->setName(p, "John Doe");
}
Thanks in advance!
- johntaxton 14y agoLet's rearrange this expression p->setName(p, "John Doe"); (p->setName) (p, "John Doe"); Here can you see that (p->setName) is entirely independent of (p, "John Doe"), so no, there is no way to pass p as an argument automatically. You say that you want to "get the ptr to a caller of a function". However there's nothing that is a "caller". You have a function pointer. Where you got that from (inside a struct perhaps) is nothing to do with the call that you later make. However, what you could do is char *setNameImp( struct Person *self, const char *name) { strcpy(self->name, name ); } char * (*setName)( struct Person *p, const char *name) { p->setName(p, name); } int main(void) { struct Person *p = (struct Person *)malloc(sizeof(struct Person)); p->setName = &setNameImp; setName(p, "John Doe"); } So have a static wrapper that calls the virtual method for you. Also, you should not be using strcpy into a buffer without checking that the buffer is large enough.
- jfaucett 14y agothanks for the detailed response! that clarifies the static wrapper method a bit that I've seen used in the mri source and other places. Yea, I should have just done strncpy but was just typing in a quick example and didn't think buffer overflows would be an issue :)
- deleted 14y ago[deleted]