Python instance method in C

后端 未结 3 2094
臣服心动
臣服心动 2021-01-06 18:14

Consider the following Python (3.x) code:

class Foo(object):
    def bar(self):
        pass
foo = Foo()

How to write the same functionalit

3条回答
  •  旧时难觅i
    2021-01-06 18:36

    You can't! C does not have "classes", it only has structs. And a struct cannot have code (methods or functions).

    You can, however, fake it with function pointers:

    /* struct object has 1 member, namely a pointer to a function */
    struct object {
        int (*class)(void);
    };
    
    /* create a variable of type `struct object` and call it `new` */
    struct object new;
    /* make its `class` member point to the `rand()` function */
    new.class = rand;
    
    /* now call the "object method" */
    new.class();
    

提交回复
热议问题