question about call cpp class constructer without new , and define cpp delegate
evilrat
evilrat666 at gmail.com
Thu Jun 27 05:57:49 UTC 2019
On Thursday, 27 June 2019 at 05:37:08 UTC, ChangLoong wrote:
> If I want call cpp class constructer without new method, is
> there a way to do that ?
If what you really want is to actually allocate using C++ new
operator from D, then that is very problematic and not portable
even across compilers on same OS.
If C++ side has poor design around this specific issue and
expects passed object to be delete'd (using the C++ delete
operator) later then you are in trouble. In that case you have to
make simple wrapper on C++ side to be able to call new/delete
from D.
If all you want is to allocate memory for object(existing buffer,
malloc, etc..) and place it there you can use emplace function
and call ctor later (see below)
https://dlang.org/phobos/core_lifetime.html#.emplace , or there
was one in "object" module IIRC
Otherwise it is also possible to just call constructors manually
using its internal name
myObj.__ctor(..params..) / this.__ctor(...)
(destructors also possible, see __dtor/__xdtor. hint: __dtor is
probably not what you want, read the docs first)
And finally to just allocate with GC using D new operator
auto myObj = new MyClass(...);
Just make sure that this object won't be delete'd from C++
> and also if the cpp api accept a delegate as parameter, how to
> create one from d and pass to cpp ?
Probably not possible. There are no delegates in C++, instead it
has pointers to member functions and limited lambdas, and there
is no analogs in D. You can try to craft it somehow to be ABI
compatible, but probably easier to just make simple wrapper on
C++ side.
IIRC member pointers is just pointer, and you provide 'this'
context on call, while in D delegate is 2 pointers - context AND
function
More information about the Digitalmars-d-learn
mailing list