Calypso/TipsAndTricks

From D Wiki
Revision as of 16:25, 12 July 2016 by Syniurge (talk | contribs) (New traits draft)
Jump to: navigation, search

Constructing C++ classes or structs inside malloc'd memory

When a C++ library expects to be granted ownership of a piece of memory, the allocation shouldn't be done by the GC unless you always keep a reference to the allocated memory, which is pointless additional work and not always possible.

Calypso provides a small runtime library which contains some commonplace utility functions, such as cppNew and cppDelete to bypass the GC while constructing C++ class/struct objects:

import cpp.memory; // cppNew and cppDelete
import (C++) std.unique_ptr;

auto testClass = cppNew!MyCppClass(...); // malloc then ctor call
unique_ptr!MyCppClass owner;
owner.reset(testClass);

// testClass will be free'd by the owner's dtor

New traits

Calypso provides a few new traits (some of them were needed for the partly library implementation of C++ member function pointers):

isCpp

static assert (__traits(isCpp, MyCppClass) == true);

getBaseOffset

struct Base { int n; };
struct Base2 { int o; };

class Derived : public Base, public Base2 {};
static assert (__traits(getBaseOffset, Derived, Base2) == int.sizeof);

Works with C++ structs and classes, and D classes.

getCppVirtualIndex