简体   繁体   English

指向和指向DLL的指针

[英]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? 是否可以将指向对象的指针传递到DLL中,对其进行初始化,然后在主应用程序中使用已初始化的指针? 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. 我已经阅读了这篇文章http://msdn.microsoft.com/zh-cn/library/ms235460.aspx但这似乎并没有给我带来什么帮助。 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. 是的,这很好,但是假设您的DLL已动态分配了缓冲区所指向的数据,则在释放它时必须小心。 There are a few ways to deal with this: 有几种方法可以解决此问题:

  • The DLL documents a method by which one should free the data (ie, CoTaskFree) DLL记录了一种方法,通过该方法可以释放数据(即CoTaskFree)
  • The DLL exposes a function that should be called to later free the data DLL公开了一个应调用的函数,以后可以释放数据
  • The DLL and the caller are using a common DLL-based runtime; DLL和调用者使用的是基于DLL的公共运行时。 this allows the caller to use the C++ delete operator 这允许调用者使用C ++ delete运算符

Yes. 是。

Assuming you are using Microsoft Visual Studio as your development environment you can export a class rather directly from a dll. 假设您使用Microsoft Visual Studio作为开发环境,则可以直接从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. 向您的dll项目中添加一个定义,例如BUILDING_THE_DLL ,下面的代码片段将从dll中导出一个c ++类批发。

#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. 这是一个高度耦合的解决方案,并且仅当您使用相同的开发环境来构建应用程序及其dll并在类定义以任何方式更改时都重新构建两者时才起作用。 this method is heavilly used by the MFC library. MFC库大量使用此方法。

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. 为了在dll和应用程序之间实现更大的独立性,通常会定义一个相对不变的接口,并使用该接口使构建更加独立,并可能使用不同的构建环境。

An implementation in your dll would look something like this: 您的dll中的实现看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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