07 January 2018

init

swoole 里面的 swFactory 和 swFactoryProcess 这两个结构看起来有点像是 swFactory 是基类,swFactoryProcess 是扩展类

class swFactory {
    ...

    public function start() {}
    public function end() {}
}

class swFactoryProcess extends swFactory {
    ...

    public function start() {}
    public function end() {}
}

在理解这个东西在 C 语言里面是怎么样实现的,对于 phper 来说,头脑发热直接去看长长的 c 代码有点无力。下面从简单的 "hello world" 代码来看看

swFactory (base class)

#include <stdio.h>
#include <stdlib.h>

struct swFactory {
    void *object;

    int (*start) (struct swFactory *factory);
    int (*end) (struct swFactory *factory);
};

int factory_start(struct swFactory *factory) {
    printf("factory start\n");
    return 0;
}

int factory_end(struct swFactory *factory) {
    printf("factory end\n");
    return 0;
}

void factory_create(struct swFactory *factory) {
    factory->start = factory_start;
    factory->end = factory_end;
}

int main(void) {
    struct swFactory *factory = (struct swFactory *) malloc (sizeof(struct swFactory));
    factory_create(factory);

    factory->start(factory);
    factory->end(factory);

    return 0;
}
➜ /usr/bin/gcc swFactory.c -o factory && ./factory

factory start
factory end

swFactoryProcess

#include <stdio.h>
#include <stdlib.h>

struct swFactory {
    void *object;

    int (*start) (struct swFactory *factory);
    int (*end) (struct swFactory *factory);
};

struct swFactoryProcess {
    int value;
};

int swFactoryProcess_start(struct swFactory *factory) {
    printf("swFactoryProcess start\n");
    return 0;
}

int swFactoryProcess_end(struct swFactory *factory) {
    printf("swFactoryProcess end\n");
    free(factory->object);
    return 0;
}

void swFactoryProcess_create(struct swFactory *factory) {
    struct swFactoryProcess *object = (struct swFactoryProcess *) malloc (sizeof(struct swFactoryProcess));
    factory->object = object;
    factory->start = swFactoryProcess_start;
    factory->end = swFactoryProcess_end;
}

// test func
void init(struct swFactory *factory) {
    struct swFactoryProcess *swFactoryProcess = factory->object;
    swFactoryProcess->value = 1000;
}

void run(struct swFactory *factory) {
    printf("res: %d\n",
           ((struct swFactoryProcess *)factory->object)->value);
}

int main(void) {
    struct swFactory *factory = (struct swFactory *) malloc (sizeof(struct swFactory));
    swFactoryProcess_create(factory);
    factory->start(factory);

    init(factory);
    run(factory);

    factory->end(factory);

    return 0;
}
➜ gcc swFactoryProcess.c -o factory_process && ./factory_process

swFactoryProcess start
res: 1000
swFactoryProcess end

end

剩下的就要自己去看代码了,C 语言功底有点弱 - -