I am trying to find a way to use C++ classes in D.
http://www.digitalmars.com/d/2.0/cpp_interface.html
D cannot call C++ special member functions, and vice versa. These include constructors, destructors, conversion operators, operator overloading, and allocators.
So, I am attempting to dumb down these C++ functions to C style function calls. Here is the proof I am working with.
class someClass {
public:
someClass();
char *whatSayYou();
};
extern "C"
{
someClass *hearMeOut();
}
#include "helper.h"
someClass::someClass()
{
}
char *someClass::whatSayYou()
{
return "Everything is gravy";
}
someClass *hearMeOut()
{
return new someClass;
}
import std.stdio;
int main(string[] args)
{
someClass *awesomeExample = hearMeOut();
char *shoutoutToTheWorld = awesomeExample.whatSayYou();
writefln(std.string.toString(shoutoutToTheWorld));
return 0;
}
extern (C++)
{
interface someClass
{
char *whatSayYou();
}
someClass *hearMeOut();
}
And here is how I complied it.
g++-4.3 -c -I code/dg3d_helper -I /usr/local/include/ -o code/dg3d_helper/helper.o code/dg3d_helper/helper.cpp
code/dg3d_helper/helper.cpp: In member function ‘char* someClass::whatSayYou()’:
code/dg3d_helper/helper.cpp:19: warning: deprecated conversion from string constant to ‘char*’
gdc-4.3 -g -c -I code/ -o code/main.o code/main.d
gdc-4.3 -g -I code/ -o main code/dg3d_helper/helper.o code/main.o -lstdc++
And I get a segmentation fault as soon as the method is called.
Program received signal SIGSEGV, Segmentation fault.
0x0000000000402fa0 in _Dmain (args=...) at code/main.d:7
7 char *shoutoutToTheWorld = awesomeExample.whatSayYou();
(gdb) bt
#0 0x0000000000402fa0 in _Dmain (args=...) at code/main.d:7
#1 0x000000000041b1aa in _D9dgccmain211_d_run_mainUiPPaPUAAaZiZi2goMFZv ()
#2 0x000000000041b235 in _d_run_main ()
#3 0x00002aaaab8cfc4d in __libc_start_main () from /lib/libc.so.6
#4 0x0000000000402d59 in _start ()
Your C++ version returns by value.
Your D version expects it to return by reference.
Essentially, your C++ version sticks a copy of someClass on the stack. D thinks that C++ will have put a pointer on the stack. It tries to interpret the copy of someClass as a pointer, and bad things happen.
The problem is that in D, classes and interfaces are always returned by reference. C++ returns everything by value unless you indicate that its either a reference or a pointer.
Thus you need this:
someClass * hearMeOut() { return new someClass; }
Don't forget to delete it later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With