Interfacing with basic C++ class
Riccardo M
asd at asd.asd
Thu Sep 29 12:49:06 UTC 2022
On Thursday, 29 September 2022 at 11:13:15 UTC, Ogi wrote:
> Ali is correct. However, you don’t have to change anything on
> the C++ side, just map C++ class to D struct:
> [...]
Thanks, this works perfectly.
Now i see that I can even instantiate directly from D, calling
the default ctor, calling the custom ctor or even overriding the
custom ctor in D (the fact that ctors could be called, in
contrast with docs, was in fact hinted at DConf 2022 as suggested
by Ali).
So it turns out that D's structs are a much better match for
C++'s classes in this case. But why is this? Can you elaborate?
It must have to do with the fact that D structs are passed by
value?
Now this D code runs as expected:
```
// D
extern(C++, class) {
struct MyClass {
public:
int field;
this(int a);
int add(int asd);
}
MyClass* instantiate(int asd);
}
void main()
{
import std : writeln;
auto myclass = instantiate(100); //actually, instantiation
through C++ is not required any longer
assert(myclass.field == 100);
auto myclass2 = new MyClass;
assert(myclass2.field == 0);
auto myclass3 = new MyClass(50);
assert(myclass3.field == 50);
assert(myclass3.add(40) == 90);
}
```
However the 'add' function only links correctly if C++ has the
function body defined outside of its class.
```
// C++
int MyClass::add(int asd) {
return field + asd;
}
```
If the function is defined inside its class, it is an undefined
reference at link time. Once again I ask for clarifications and
workarounds, if possible.
Thanks
More information about the Digitalmars-d-learn
mailing list