Visual Studio c++ LoadLibary error: The program ca

2019-09-06 15:55发布

问题:

I'm trying to connect my program to a dll.

Connect code:

HINSTANCE lib;

    lib = LoadLibrary("DLL.dll");
    if (lib)
    {
        cout << "Libary Loaded !";
        FreeLibrary(lib);
    }
    else
    {
        cout<<GetLastError();
    }

DLL code(at DLL.cpp):

#include "pch.h"
#include "DLL.h"

#include<iostream>
using namespace std;

int f()
{
    return 11;
}

Once I run the program I get this error:

The program can't start because <dllname> is missing from your computer.

After each dll request I downloaded the dll from the internet and put it into the folder where the dll and the program are. Here are some of the dll I requested:

  1. VCRUNTIME140_APP.dll
  2. api-ms-win-core-processthreads-l1-1-2.dll

Once I get that error after clicking 'OK' button I get GetLastError() = 126.

I tried to link my program to the lib VCRUNTIME140_APP.dll just to check if it is going to load the library and it did. So the problem is probably in the library I try to connect to.

I work with Visual Studio 2015.Both the DLL and the program are compiled in x86(32bit). I have all redistribution packages installed. I tried with x64(64bit) but got same errors and the same dlls requests. I tried to put DLL in build and in debug folders both didn't work.

I also tried using **LoadLibaryA** and **LoadLibaryW** but these didn't work as well.

PS: Just tried dll I created in CodeBlocks instead of Visual Studio 2015 and it connected. Should be a Visual Studio Compiler specific problem.

回答1:

If you look to the syntax of LoadLibrary function:

HMODULE WINAPI LoadLibrary(
   _In_ LPCTSTR lpFileName
);

You see that there is no option to specify from where to load your library

Instead use the function LoadLibraryEx witch has the following syntax:

HMODULE WINAPI LoadLibraryEx(
   _In_       LPCTSTR lpFileName,
   _Reserved_ HANDLE  hFile,
   _In_       DWORD   dwFlags
);

So with the use of dwFlags parameter, you can now specify from where your program can try to load your library.

example of dwFlags:

LOAD_LIBRARY_SEARCH_APPLICATION_DIR 0x00000200:

witch means:

 If this value is used, the application's installation directory is searched  
 for the DLL and its dependencies. Directories in the standard search path  
 are not searched.

So to resume, you have to use the dwFlags parameter you want in order to find your dll.