How to get its own handle in a DLL

Source: Internet
Author: User

Questions: DLL to get the folder in which the DLL itself is located, not the keynote program. Using GetCurrentDirectory to get the EXE key program is located in the directory, does not meet my requirements, with GetModuleFileName can only be obtained in DllMain, because DllMain The first parameter, HINSTANCE, is the DLL module and GetModuleFileName () only gets the DLL path by passing in the DLL module handle.

However, if the project is not a DllMain project, but the Win32 DLL is checked for MFC options, the entry function is int _tmain (int argc, tchar* argv[], tchar* envp[]), without DllMain as the entry HINSTANCE, how do you get the module handle of the DLL ?

Method 1: Pass in the handle

Save the HInstance in DllMain with a global variable and pass it to: GetModuleFileName where you need it.

Method 2: Pass in the DLL name

Hmodule hmod = GetModuleHandle (_t ("MyDLL.DLL")); if (hmod! = NULL) {    TCHAR Szbuffer[max_path] = {0};    GetModuleFileName (Hmod, Szbuffer, sizeof (szbuffer)/sizeof (TCHAR)-1);

Method 3: General approach

TCHAR Szdllfolder[max_path + 1]; GetModuleFileName (AfxGetApp ()->m_hinstance, Szdllfolder, MAX_PATH);

just to add a little bit of clarification, VC has three types of DLL projects :

(1) MFC extension DLLs (DLLs are loaded automatically into the Ingress function DllMain, but preferably used by the export interface)

extern "C" int apientrydllmain (hinstance hinstance, DWORD dwreason, LPVOID lpreserved)

(2) Win32 standard DLL (DLL is loaded automatically into the entry function DllMain, but preferably through the export interface )

BOOL apientry DllMain (hmodule hmodule,                       DWORD  ul_reason_for_call,                       lpvoid lpreserved)
(3) Win32 check MFC Option DLL (DLL isLoadingdoes not enter function _tmain (), only provides export interface)

int _tmain (int argc, tchar* argv[], tchar* envp[])


How to get its own handle in a DLL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.