开发者

DLL used by a program, where are the variables declared in it stored?

开发者 https://www.devze.com 2023-03-11 21:57 出处:网络
I have a program (not mine, have no source code) which exposes an interface so I can write a DLL which will be called by my program.Now I wondered when I declare some variable in this DLL I make, in w

I have a program (not mine, have no source code) which exposes an interface so I can write a DLL which will be called by my program. Now I wondered when I declare some variable in this DLL I make, in what memory space is this going to be stored?

I mean, it's just gonna sit in the memory space of the EXE's address space, right? How开发者_C百科 is the DLL loaded in regards to the EXE though? I thought a DLL was only ever loaded in memory once, so how does that work in relation to me creating local variables in my DLL? (like objects, classes etc)


A DLL is loaded once per process. Once upon a time DLLs were shared between processes, but that hasn't been the case since Windows 3.1 went the way of the dodo.

Any global variables that you declare in your DLL will be stored in a data page. A different page from the EXE's global variables, mind.

Now, if you allocate memory on the heap, whether or not your allocations are mixed in with the EXEs depend on which heap you use. If both EXE and DLL use the same runtime linked as a DLL then they will both get memory from the same heap. If they have different runtimes, or link against runtime statically, they'll get different heaps. This becomes a very big can of worms, so I shan't go any further here.


Your DLL will declare a DllMain which is the equivalent to the entry point in a regular executable. When your DLL is loaded your DLLMain gets called. Here is a link to the best practices of what should be done in there.

Usually you will do some sort of intialisation there. When your DLL is loaded, it is loaded into the virtual memory space of the executable that called LoadLibrary. LoadLibrary handles all the mapping and relocations that need to be dealt with. From this point all memory you allocate or modify through your DLL is in the same virtual memory space as the process it's mapped into.

Presumably the executable interfaces by loading your DLL then calling some sort of exported function in it. Basically everything that you do once your DLL is loaded will be within the memory space of the process it is loaded into.

If you want to know more about exactly what goes on when your DLL is loaded you should look into the semantics of LoadLibrary().

0

精彩评论

暂无评论...
验证码 换一张
取 消