简体   繁体   中英

Pointers in and out of DLLs

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...

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 (ie, 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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM