0

I am trying to share a global variable between my_exe.exe and my_dll.dll. I would expect changes to my_var made inside of my_exe.cpp to be reflected in my_dll.cpp at runtime. I expect the exe to have the dll loaded into it's address space and therefore making my_var shared between the 2. However changes made to my_var are not being reflected on either side. I am adding mydll.lib to the linker inputs for the my_exe project. my_exe.cpp

extern __declspec(dllimport) float my_var;
typedef void (*called_from_exe)();

int main()
{
    HMODULE my_dll = LoadLibraryW("my_dll.dll");
    called_from_exe = (called_from_exe_t)GetProcAddress(my_dll, "called_from_exe");

   my_var = 7.f;
   called_from_exe();
}

my_dll.cpp

__declspec(dllexport) float my_var = 2.f;

extern "C" __declspec(dllexport) void called_from_exe()
{
   print(my_var) // prints 0.00 instead of 7.00
}
mbl
  • 805
  • 11
  • 18
  • Sorry I forgot to mention I am linking against the .lib. I modified my post to indicate that. – mbl May 06 '21 at 10:56
  • You are not linking in the conventional sense when you dynamically load the library. I think you will find that you can write to my_var before loading the library. The only shared symbol in your address space is called_from_exe – stark May 06 '21 at 11:07
  • Related (possible duplicate): [Is global variable in a shared library / dll, shared across process?](https://stackoverflow.com/q/1979303/10871073). Especially the top-voted answer. – Adrian Mole May 06 '21 at 11:24
  • 1
    @AdrianMole My question only involves 1 process, which is `my_exe.exe`. The DLL is loaded into the address space of `my_exe.exe` and is part of it's address space once it's loaded. – mbl May 06 '21 at 11:28
  • @stark It looks like you're right. If I export/import the function by using `dllexport` and `dllimport` instead of `LoadLibrary` I can modify `my_var` inside of that function and the changes are reflected on both sides. Why is it different though? I thought those were just 2 different ways to do dynamic linking. – mbl May 06 '21 at 11:42
  • If you link to a library implicitly at the time you load your program (iusing dllimport as you say) then all exported symbols are shared. If you load the library explicily at runtime (using LoadLibrary) then your symbols are already resolved to memory locations. The only symbols from the DLL you can reference are ones you look up with GetProcAddress – stark May 06 '21 at 12:49
  • Great answer, thank you! – mbl May 06 '21 at 12:49

0 Answers0