Difference between revisions of "Calypso/TipsAndTricks"

From D Wiki
Jump to: navigation, search
(Constructing C++ classes or structs on malloc'd memory)
m (Constructing C++ classes or structs on malloc'd memory)
Line 1: Line 1:
== Constructing C++ classes or structs on malloc'd memory ==
+
== Constructing C++ classes or structs inside malloc'd memory ==
  
When a C++ library expects to be granted ownership on a piece of memory, the allocation shouldn't be done by the GC unless you keep a reference to the allocated memory all the time, which is pointless additional work and not always possible.
+
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 common utility functions, such as <code>cppNew</code> and <code>cppDelete</code> to bypass the GC while constructing C++ class/struct objects:
+
Calypso provides a small runtime library which contains some commonplace utility functions, such as <code>cppNew</code> and <code>cppDelete</code> to bypass the GC while constructing C++ class/struct objects:
  
 
<syntaxhighlight lang="D">
 
<syntaxhighlight lang="D">
Line 9: Line 9:
 
import (C++) std.unique_ptr;
 
import (C++) std.unique_ptr;
  
auto testClass = cppNew!MyCppClass(); // malloc then ctor call
+
auto testClass = cppNew!MyCppClass(...); // malloc then ctor call
 
unique_ptr!MyCppClass owner;
 
unique_ptr!MyCppClass owner;
 
owner.reset(testClass);
 
owner.reset(testClass);

Revision as of 21:02, 27 June 2016

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