|
-
July 30th, 2005, 08:25 PM
#1
Passing FILE* to DLL
I have the following in my DLL:
Code:
MessageLogger *logger=NULL;
HINSTANCE g_hmodThisDll = NULL;
MessageLogger* getMessageLogger()
{
return logger;
}
BOOL APIENTRY DllMain( HINSTANCE hInstance,
DWORD dwReason,
LPVOID lpReserved
)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
{
g_hmodThisDll = hInstance;
logger = new MessageLogger;
}
break;
case DLL_PROCESS_DETACH:
if (logger)
delete logger;
break;
I am exporting MessageLogger* getMessageLogger() and the whole MessageLogger class.
MessageLogger has the following function:
Code:
void MessageLogger::setFile(FILE * pFile)
{
m_pFile = pFile;
}
My main executable calls getMessageLogger() to get a pointer to the MessageLogger created by the DLL.
Is this OK to do?
My main program then opens a file and passes the pointer to set file:
Code:
FILE *f = fopen("DateTime.Log","w");
logger->setFile(f);
My problem is that pFile contains a bad pointer when it gets to the DLL. How do I pass this file pointer to the DLL?
-
July 31st, 2005, 01:21 AM
#2
Re: Passing FILE* to DLL
Never pass a FILE * to a DLL, or a DLL pass to you a FILE *.
The reason is that FILE* is a structure that is highly dependent on compiler version and compiler. The internals of a FILE* for VC 6.0 Service pack 1, may be different than a FILE * for Service pack 3 or 4. It's worse if the DLL was built with VC 6, and the app was built with VC 7.0 or another brand of compiler.
Also, FILE* may allocate memory internally and release memory during operation. You can't pass types that do internal memory management back and forth between app and DLL, unless both app and DLL use the DLL runtime library.
But even so, the first point is the most important -- FILE * may have the same name, but more than likely different internals between compilers and compiler versions, which causes crashes and possibly undefined behavior.
Regards,
Paul McKenzie
-
July 31st, 2005, 10:12 AM
#3
Re: Passing FILE* to DLL
Thanks Paul. I have already rethought my design. I am now going to have a "device" class. the DLL will be the one that creates the FILE* via the device class constructor. Is this OK?
P.S. The DLL was created in Visual C++ 2003 .NET. My test program was written in VC6. From your information, I assume this is why I had the problem.
-
July 31st, 2005, 10:21 AM
#4
Re: Passing FILE* to DLL
I wonder if it is possible with fstream or the windows file functions (CreateFile, WriteFile, ReadFile).
Please don't forget to rate users who helped you!
-
July 31st, 2005, 10:56 AM
#5
Re: Passing FILE* to DLL
 Originally Posted by philkr
I wonder if it is possible with fstream or the windows file functions (CreateFile, WriteFile, ReadFile).
you can pass HANDLE to WriteFile(), ReadFile() etc. -- that is their intended purpose.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|