DLL file mapping

        -- DLL notes 2 of <Windows via C/C++>

 

Let’s begin this topic with a question about exporting variables in DLL:

Assume one process import a variable from a DLL, and change the value, then if another process import the same variable from the DLL, will the variable have the value the former process assigned?

I once thought the data should be the same to all the processes, because the DLL have been mapped into to all process’ address. To insure my thoughts I did a little experiment. But the test result is opposite: Each process have a separate copy of data, including integer and char array type.

According to the test result, I think, all the function is mapped into the process’s virtual address, but the variable outputted is allocated in the process’s address, and initialed with the value in DLL.

Here is the explanation from the book:

Once a DLL's file image is mapped into the calling process' address space, the DLL's functions are available to all the threads running within the process. When a thread calls a DLL function, the DLL function looks at the thread's stack to retrieve its passed parameters and uses the thread's stack for any local variables that it needs. In addition, any objects created by code in the DLL's functions are owned by the calling thread or process—a DLL never owns anything.

When one process maps a DLL image file into its address space, the system creates instances of the global and static data variables as well. (Though it doesn’t explicitly say the global data are create in process’s address.)

And following is another interesting question: what about two DLLs contain the same function?

As the testing result, when link two DLLs containing the same function name In the Visual C++, the compiler won’t report error, but call the function from the first DLL that linked to.

Actually the compiler needs to know which .lib file to link. And you may set the project dependencies to tell the compiler which .lib file to link. And you may also use #pragma comment (lib, ".//debug//myDll.lib"), and the third way is to set input in the link setting.

 

In the book it’s also reminds that avoid exporting variables

In real life, you should avoid exporting variables because this removes a level of abstraction in your code and makes it more difficult to maintain your DLL's code.

In addition, C++ classes can be exported only if the modules importing the C++ class are compiled using a compiler from the same vendor. For this reason, you should also avoid exporting C++ classes unless you know that the executable module developers use the same tools as the DLL module developers.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值