0

Good time of day, everyone!

I have some questions about .dll programming in C++, it's rather new for me.

1) If I want to create DLL with a multiple classes, but I still want to create abstract interface for each class, should I create one header file for interfaces, or create separate multiple headers for each abstract class? And what should I do with .cpp implementation of factory functions?

2) If I create object and factory function, and gets a pointer to instance, can I just call "delete" in program when I want to free that memory? I think, that object is placed in dll's pages and there may be some problems. What should I do to properly free memory in this case?

3) I read, that if more than one process binds .dll - dll creates separate individual instances of global variables for each project. Does it right? Then I have two questions if it is true:

3.1) What happens with static members in dll? What if I want to create a singleton manager, can I place it in dll?

3.2) If I have Core.dll and Graphics.dll, Sound.dll and Physics.dll. Core.dll has a global variable (or a singleton manager in my real case). Will the other dlls work with one instance of singleton, or other? (each dll uses Core.dll)

I apologize for my weak English and many questions in one topic :)

Thank you for your attention and answers.

4

1 回答 1

1

1:这主要取决于您,取决于项目的规模。在一些小的事情上它无关紧要,所以保持简单并有一个标题。在较大的项目中,最好尽可能减少不必要的相互依赖——因此将它们放在单独的文件中。您可以始终创建仅包含其他内容的“all.h”。

2:是的,如果 DLL 和 EXE 都链接到多线程 DLL CRT。除非您知道自己在做什么,否则请始终使用它,因为它是最安全的,并且会按照您的预期进行 - 它会导致 exe 和 dll 能够共享堆,就好像它们是单个可执行文件一样。您可以自由地在 dll 中“新建 Object()”和在 exe 中“删除 obj”。注意:混合不同版本的 EXE 和 DLL 可能会引入非常微妙的错误(例如,如果类/结构定义发生更改),所以不要这样做。

3:每个进程都有自己独立的内存空间(除非你专门做某些事情来尝试获得一些共享内存)。不允许进程访问其他进程的内存。

3.1:我强烈建议你避免使用全局状态。(全局静态常量是可以的)。全局变量会导致许多意想不到的困难问题,并且 Windows DLL 中的全局变量具有许多额外的复杂性。从长远来看,在 EXE 必须调用的 DLL 中具有显式的“初始化/取消初始化”函数会更好。

但是,dll 中的全局静态变量与可执行文件中的差异不大……它们在加载 DLL 时以几乎相同的方式进行初始化。(当您动态加载 DLL 时,事情会变得更加复杂,但让我们在这里忽略它)。

3.2:是的,他们会在单个实例上工作——但无论如何都不要这样做,你最终会后悔的。显式初始化要好得多,因为您无法控制构造全局变量的顺序,这会很快导致非常困难的初始化问题。

于 2013-09-21T17:36:56.700 回答