Heap fucntion calls

Simen Kjaeraas simen.kjaras at gmail.com
Thu Sep 22 11:58:36 PDT 2011


On Thu, 22 Sep 2011 00:43:09 +0200, deadalnix <deadalnix at gmail.com> wrote:

> Great answer ! Thank you very much, it answered almost everything !
>
> But what about, in the exemple you gave me (which is great by the way)  
> if foo as parameters ? Those parameters are passed on the stack by copy  
> to the function, and then, copied to the heap (resulting in two copies) ?

Oui. In that case:

void foo(int n, ref int i) { // Adding in a ref, for good measure.
     n = 2;
     int x = 5;
     auto dg = () {x = 4; n = 3; i = 2;};
     dg();
}

becomes:

typedef struct foo_dg_1_delegate {
     void (*funcptr)(struct foo_dg_1_context*);
     void* ptr;
};

typedef struct foo_dg_1_context {
     int x;
     int n;
     int* i;
};

void foo_dg_1(struct foo_dg_1_context* ctx) {
     ctx->x = 4;
     ctx->n = 3;
     *ctx->i = 2;
}

void foo(int n, int* i) {
     struct foo_dg_1_delegate dg;
     struct foo_dg_1_context* ctx = (struct  
foo_dg_1_context*)malloc(sizeof(struct foo_dg_1_context));
     dg.funcptr = &foo_dg_1;
     dg.ptr = ctx;
     ctx->x = 5;
     ctx->n = n; // Unnecessary initialization, but conceptually happens.
     ctx->i = i;

     ctx->n = 2;
     dg.funcptr(dg.ptr);
}

-- 
   Simen


More information about the Digitalmars-d-learn mailing list