Export class from executable to dll

I need to use the class defined in the executable in the DLL (the DLL and the executable are compiled by the same compiler). But I do not want the source code of this class definition to be available for the DLL, only a declaration.

One of the possible ways to do this is to make all the necessary methods of the class virtual(so that the DLL linker does not need definitions of these methods). The disadvantages of this approach are:

  • I cannot create objects of exported classes in DLL code using new(a create additional functions in executable code).
  • I need to do all of these methods virtual, even if otherwise they do not need to be virtual.

There is a way to export a class from a DLL to an executable file using the extended attribute of __declspec(dllexport)the storage class class __declspec(dllexport). Is there a way to export a class from an executable to a DLL using the same technique?

My old Borland C 6 compiler does not allow me to create an import library while building an executable project. (So, when compiling a DLL, the linker gives me unresolved external error messages for all imported methods of a non-virtual class.) Is this a limitation of this compiler itself, or maybe I'm missing something important?

+3
source share
3 answers

, MS VS dllexport exe DLL. , DLL Exe .

+3

DLL, .

DLL.

ETA: , , EXE Visual Studio 2008. , , , __declspec (dllexport).

+2

, . EXE , , , :

Step 1: Create a wrapper API for your class, like this (probably don't compile, but you get the idea):

// Yes, need some 32 bit/64 bit checks here
#define MYHANDLE unsigned int

__declspec(dllexport) MYHANDLE MyClassNewInstance() {
   MyClass* ptr = new MyClass();
   return (MYHANDLE)ptr;
}

__delspec(dllexport) MyClassDoSomething( MYHANDLE handle, int parm ) {
  MyClass* ptr = (MyClass*)handle;
  ptr->DoSomething(parm);
}

etc..

Step 2: To actually get the C functions from the EXE for use in the DLL, use the Win32 API functions GetModuleHandle () and GetProcAddress ().

Step 3. Create a proxy class in your DLL. Methods in the proxy class do nothing but call their C-function counterparts from EXE.

This will provide a β€œreal” implementation of your class from the DLL. This is a hack, but it will probably work.

0
source

Source: https://habr.com/ru/post/1703952/


All Articles