

Ask HN: Work Around for passing C Pointers - jfaucett

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.<p><pre><code>  struct Person {
   char name[32];
   char * (*setName)( struct Person *, const char *); 
  };

  char *setName( struct Person *self, const char *name) {
    strcpy(self-&#62;name, name );
  }
 
  int main(void) {
    struct Person *p = (struct Person *)malloc(sizeof(struct Person));
    p-&#62;setName = &#38;setName;

    // here I'd really like to not have to pass the ptr 'p'
    // is there any way to do this?
    p-&#62;setName(p, "John Doe");
  }
</code></pre>
Thanks in advance!
======
johntaxton
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
thanks 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 :)

