Click to See Complete Forum and Search --> : Passing FILE* to DLL


spinnaker
July 30th, 2005, 08:25 PM
I have the following in my DLL:



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:



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:


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?

Paul McKenzie
July 31st, 2005, 01:21 AM
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

spinnaker
July 31st, 2005, 10:12 AM
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.

philkr
July 31st, 2005, 10:21 AM
I wonder if it is possible with fstream or the windows file functions (CreateFile, WriteFile, ReadFile).

stober
July 31st, 2005, 10:56 AM
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. :rolleyes: