Re: Accessing global variables in EXE from DLL
From: Jerry Coffin (jcoffin_at_taeus.us)
Date: 05/21/04
- Next message: seia0106: "too long execution time and access violation error"
- Previous message: Nathan Holt: "Re: PostThreadMessage to CWinThread failing to be processed."
- In reply to: Abhijit Patait: "Accessing global variables in EXE from DLL"
- Messages sorted by: [ date ] [ thread ]
Date: Fri, 21 May 2004 11:08:59 -0600
In article <473bc1dc.0405191124.652f05a2@posting.google.com>,
abhi_junk@hotmail.com says...
> Is there any way I can access the global variables declared in the EXE
> file from a DLL?
It's possible, but it's usually a bad (or terrible) idea.
Maybe if being told it's a bad idea won't dissuade you from this
course, the fact that it's ugly, non-portable, and difficult to
manage will.
I feel a little like I'm handing a loaded gun to a nine year-old and
saying "here's the safety and here's the trigger -- be sure NOT to
push the safety this way and then pull the trigger that way...", but
here's some code that does what you've asked:
// exportdll.h:
void __declspec(dllimport) dllfunc(void);
// exportmain.cpp:
#include "exportdll.h"
#include <stdio.h>
int __declspec(dllexport) junk;
int main() {
junk = 0;
printf("value before calling dllfunc: %d\n", junk);
dllfunc();
printf("value after calling dllfunc: %d\n", junk);
return 0;
}
// exportdll.cpp:
#include <windows.h>
extern int __declspec(dllimport) junk;
void __declspec(dllexport) dllfunc() {
junk = 1;
}
BOOL DllMain(HINSTANCE, DWORD, void *) {
return TRUE;
}
Building up a working executable is rather an ugly process. The
problem is that you have a circular dependency: the executable
depends on the DLL and the DLL depends on the executable (another
sign that this is a bad idea).
The trick to building this successfully is to expect (and more or
less ignore) some error messages while executing the following steps:
cl exportmain.cpp
cl /LD exportdll.cpp exportmain.lib
cl exportmain.cpp exportdll.lib
The first attempt at compiling exportmain.cpp will fail to create an
executable, but it WILL create a .lib file. That allows you to build
the DLL, and its .lib file, which allows you to build the executable.
The final word: this is a bad idea. The code and build sequence
above are really intended only to show just HOW bad an idea it is,
NOT as an example to be emulated. It can be made to work, for a
sufficiently loose definition of the word, but your application as a
whole will be much the worse for using it, so DON'T DO IT!
--
Later,
Jerry.
The universe is a figment of its own imagination.
- Next message: seia0106: "too long execution time and access violation error"
- Previous message: Nathan Holt: "Re: PostThreadMessage to CWinThread failing to be processed."
- In reply to: Abhijit Patait: "Accessing global variables in EXE from DLL"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|