www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Allocating memory in D shared library when accessed from C++

Hello everyone,

I would like to ask you about linking D shared objects (.dll and .so) 
from a C++ program.

Say I have this C++ loader:

 typedef int (*MagicFunction) ();

 HMODULE handle = LoadLibraryA("DLibrary.dll");
 if (handle)
 {
   MagicFunction fn = (MagicFunction) GetProcAddress(handle, "_magicFunction");
   std::cout<<fn()<<std::endl;
 }

and this D library:
 class Something {}

 export extern (C) int magicNumber()
 {
   Something desc = new Something();
   return 9;
 }

 extern (Windows)
 BOOL DllMain(HINSTANCE hInstance, ULONG ulReason, LPVOID pvReserved)
 {
     final switch (ulReason)
     {
 	case DLL_PROCESS_ATTACH:
 	    g_hInst = hInstance;
 	    dll_process_attach( hInstance, true );
 	    break;

 	case DLL_PROCESS_DETACH:
 	    dll_process_detach( hInstance, true );
 	    break;

 	case DLL_THREAD_ATTACH:
 	    dll_thread_attach( true, true );
 	    break;

 	case DLL_THREAD_DETACH:
 	    dll_thread_detach( true, true );
 	    break;
     }
     return true;
 }

then whenever the code reaches the call:
 Something desc = new Something();

I thought that the GC is angry with me, so I have tried to use malloc, but to no avail. Error is the same... Can you please give me a hint what I am doing wrong? Also I am curious why is the first name of exported function underscored and all the others are not. Thanks for your time. Martin
Dec 19 2011