'how to use AddDllDirectory() function to add dll locations for load-time dynamic linking

I have an application that has the following structure:

app dir
...exe dir
......app.exe
......somedll1.dll
......somedll2.dll
...subdir1
......subdir1_dll1.dll
......subdir1_dll2.dll
...subdir2
......subdir2_dll1.dll
......subdir2_dll2.dll

Due to how the app.exe works (which I cannot change as it's closed source), it searches for the dll1 in each subdir, but not the dll2. I would need to place the dll2 into the exe dir, but this introduces problems:

  1. Each subdir dll1 loads the dll2, and each need their own memory, so I cannot share the memory of dll2 between each dll1.
  2. While currently the dll2 of each subdir is the same, there is no guarantee that will be the same in the future
  3. Even if it shared memory was a possibility, due to project specifics, it's less intuitive and elegant to place the dll in exe dir.

Given these issues, I'm trying to use the libloaderapi.h function AddDllDirectory in each dll1 to specify where to search for the dll2. The problem is that I cannot figure out how to use it. The docs say:

DLL_DIRECTORY_COOKIE AddDllDirectory(
  [in] PCWSTR NewDirectory
);

An absolute path to the directory to add to the search path. For example, to add the directory Dir2 to the process DLL search path, specify \Dir2

But I can't get to use it correctly. If I define the function and in the next line call it:

DLL_DIRECTORY_COOKIE AddDllDirectory(
    PCWSTR NewDirectory
);

AddDllDirectory(("c:\\"));

I get various warnings in the DLL_DIRECTORY_COOKIE AddDllDirectory line :

Can't find definition for AddDllDirectory
Declaration is not compatible with "int AddDllDirectory(<error-type>)"
C28251: Incoherent annotation for AddDllDirectory. This instance has no annotations.

And many errors in the AddDllDirectory(("c:\\")); line:

Missing ")" before "("
Missing ")" before string
Function returns a function
...

Even removing the call to the function yields error, simply including this line in the code:

DLL_DIRECTORY_COOKIE AddDllDirectory(
    PCWSTR NewDirectory
);

Already gives the following warnings:

C28251: Incoherent annotation for AddDllDirectory. This instance has no annotations.

And when compiling, the following warnings:

warning C4273: 'AddDllDirectory': incoherent dll linking
message : look at the previous definition of 'AddDllDirectory'

I tried to look for examples online but none seem to work.

I am using #include <libloaderapi.h> and #include <windows.h>



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source