What is the Correct way to Malloc in @nogc section?
Foo via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Feb 12 15:52:40 PST 2015
On Thursday, 12 February 2015 at 23:27:51 UTC, Kitt wrote:
> I'm currently trying to write a personal Associate Array class
> that can be used in @nogc sections. Obviously, this means I'll
> want to use malloc/free, however I'm not sure what the
> "Correct" way to do this is. In a few places online I've seen
> code for custom "_new" and "_delete" functions similar to this:
>
> [code]
> T _new(T, Args...) (Args args) {
> size_t objSize;
> static if(is (ValType == class))
> objSize = __traits(classInstanceSize, T);
> else
> objSize = T.sizeof;
>
> void* tmp = core.stdc.stdlib.malloc(objSize);
> if (!tmp) throw new Exception("Memory allocation failed");
> void[] mem = tmp[0..objSize];
> T obj = emplace!(T, Args)(mem, args);
> return obj;
> }
>
> void _delete(T)(T obj) {
> clear(obj);
> core.stdc.stdlib.free(cast(void*)obj);
> }
> [/code]
>
> The Exception obviously uses the GC, and would need to be
> replaced with a printf or something; however, emplace doesn't
> have a @nogc replacement that I know of. What I'd like to know,
> from people much more knowledgeable about the ins and outs of
> D, is what the "Best" or "Correct" way to allocate and
> deallocate within @nogc sections?
>
> PS: Tangentially related, what hashing algorithm does D use?
> I've seen people suggest using typeid(object).toHash(&object);
> however, toHash isn't @nogc, so I need to write my own Hashing
> function. For the sake of consistency and peace of mind, I'd
> really like to match mine as closely to Ds internal one as
> possible.
This is something I've done recently.
Would be glad if my code will help you:
https://github.com/Dgame/m3
Especially the m3.d module could be useful for you.
More information about the Digitalmars-d-learn
mailing list