views:

169

answers:

2

Is it possible to pass a pointer to an object into a DLL, initialize it, and then use the initialized pointer in the main application? If so how? Are there any good articles on the subject, perhaps a tutorial?

I have read this article http://msdn.microsoft.com/en-us/library/ms235460.aspx But that did not seem to get me any where. Maybe I am misinterpreting it...

A: 

Yes.

Assuming you are using Microsoft Visual Studio as your development environment you can export a class rather directly from a dll. Add a define to your dll project something like BUILDING_THE_DLL and the following code snippit will export a c++ class wholesale from the dll.

#ifdef BUILDING_THE_DLL
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT __declspec(dllimport)
#endif

class EXPORT DllClass
{
....
};

This is a highly coupled solution and only works if you build the application and its dll using the same development environment, and rebuild both whenever the class definition changes in any way. this method is heavilly used by the MFC library.

To achieve a greater independence between the dll and app, one typically defines a relatively immutable interface and uses that to make builds more independent, and possibly use different build environments.

An implementation in your dll would look something like this:

struct IMyInterface {
   virtual void Destroy() =0;
   virtual void Method() = 0;
};

class MoDllObject : public IMyInterface
{
// implementation
};

bool EXPORT DllGetInterface(IMyInterface** ppOut)
{
  *ppOut = new MyDllObject();
   return true;
}
Chris Becke
+3  A: 

Yes, this is fine, but assuming your DLL has dynamically allocated the data being pointed to by the buffer, you must be careful about how you free it. There are a few ways to deal with this:

  • The DLL documents a method by which one should free the data (i.e., CoTaskFree)
  • The DLL exposes a function that should be called to later free the data
  • The DLL and the caller are using a common DLL-based runtime; this allows the caller to use the C++ delete operator
GBegen