Am 26.06.2012 19:19, schrieb Steven Schveighoffer:
On Tue, 26 Jun 2012 12:05:55 -0400, Benjamin Thaut
<[email protected]> wrote:

Am 26.06.2012 18:02, schrieb Timon Gehr:

You can cast function pointers to pure, or mark extern(C) memory
allocation functions as pure.

extern(c) is not an options as there is a structure of various
different allocators that implement a common interface which all is
written in D.

extern(C) does not mean implemented in C, it just means C linkage. You
can use arrays, classes, etc. in extern(C) functions. UFCS makes this
really easy too:

myalloc.d:

interface Allocator
{
void * _alloc(size_t size);
}

extern(C) void *alloc(Allocator a, size_t size) pure;

allocimpl.d:
import myalloc;

extern(C) void *alloc(Allocator a) // pure
{
return a._alloc(size)
}

mallocer.d:

public import myalloc;
import std.c.stdlib;

// sample allocator
class Mallocer : Allocator
{
void *_alloc(size_t size) { return malloc(size);}
}

main.d:

import mallocer;

void foo(Allocator a) pure
{
a.alloc(200);
//a._alloc(200); // fails as expected
}

void main()
{
foo(new Mallocer);
}

-Steve

Thanks this works, but it seems to be a very ugly hack just to work around the type system. Also I have templated allocator functions I can not use this trick on. This is going to be a lot of work to get done properly, so I just ignore pure for now I think.

Reply via email to