Last active
July 5, 2017 18:01
-
-
Save PetarKirov/e070f4dc4a9a3d18d6b18156ca318d91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import core.stdc.stdio : printf; | |
extern (C) void main() | |
{ | |
Base b = create!Derived; | |
b.foo(); | |
} | |
extern (C++) class Base | |
{ | |
int x = 39; | |
this() { ++x; } | |
void foo() { printf("Base.\n"); } | |
} | |
extern (C++) class Derived : Base | |
{ | |
this() { x += 2; } | |
override void foo() { printf("Derived - x = %d.\n", x); } | |
} | |
T create(T)() if (is(T == class)) | |
{ | |
import core.stdc.stdlib : malloc; | |
import core.stdc.string : memcpy; | |
enum size = __traits(classInstanceSize, T); | |
void[] mem = malloc(size)[0 .. size]; | |
auto init = typeid(T).initializer; | |
memcpy(mem.ptr, init.ptr, size); | |
T result = cast(T)mem.ptr; | |
static if (__traits(compiles, result.__ctor())) | |
result.__ctor(); | |
return result; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ dmd --version | |
DMD64 D Compiler v2.075.0-b1 | |
Copyright (c) 1999-2017 by Digital Mars written by Walter Bright | |
$ dmd -betterC extern_cpp_class.d && ./extern_cpp_class | |
Derived - x = 42. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment