Interfacing with basic C++ class

Riccardo M asd at asd.asd
Wed Sep 28 19:57:10 UTC 2022


I think I am stuck in the easiest of the issues and yet it seems 
I cannot get around this.
I have a C++ file:
```
class MyClass {
public:
     int field;
     MyClass(int a) : field(a) {}

     int add(int asd) {
         return asd + 1;
     }
};

MyClass* instantiate(int asd) {
     return new MyClass(asd);
}
```
and a D file:
```
extern(C++) {
	class MyClass {
		public:	
			int field;
			@disable this();
			final int add(int asd);
		}

	MyClass instantiate(int asd);
}

void main()
{
	import std : writeln;
	auto myclass = instantiate(100);
	writeln(myclass.field);
}
```
This is a very simplified version of the dlang official example 
of interfacing with C++ classes.

When I compile, I can't correctly read 'field'. What I do:
```
g++ -c cpp.cpp
dmd app.d cpp.o -L-lstdc++
./app
```
What I get:
```
0
```
Instead of the expected 100.

Care to help me understand what am I doing wrong?

Side question: it seems that I need to declare every class method 
as "final" otherwise I get  undefined references during linking. 
Is this expected behaviour?

Thanks


More information about the Digitalmars-d-learn mailing list