3 ms·
Let'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 (
by johntaxton 14y ago
Let'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 :)