Link to home
Start Free TrialLog in
Avatar of jpf080698
jpf080698

asked on

sharing a file pointer with a dll

I'd like to open and close a file in a dll from an application. The aim is that the aplication and the dll-routines write into the same file.
After trying unsuccessfully to export the file pointer from the dll to the application, I wrote the open and close file routines in the dll. Doesn't work better...
I wrote then:
in dll header file:
#define VD_DLL __declspec (dllexport)
extern VD_DLL FILE *openSFile(char *fileName)
extern VD_DLL void  closeSFile(FILE *filePointer);

in dll code:
VD_DLL FILE *openSFile (char *fileName)
{
  return (fopen (fileName,"w"));
}
VD_DLL void closeSFile (FILE *filePointer)
{
  fclose (filePointer);
}

in exe header:
#define VD_DLL __declspec (dllexport)
extern VD_DLL FILE *openSFile(char *fileName)
extern VD_DLL void  closeSFile(FILE *filePointer);

in exe code:
main()
{
  FILE *fp;

  openSFile ("file.txt");
  closeSFile (fp);
}

This program causes an assertion failure. How could it work?
Avatar of plaroche
plaroche

have you tried assigning the file pointer?

main()
{
  FILE *fp;

  fp = openSFile ("file.txt");
  closeSFile (fp);
}


Avatar of jpf080698

ASKER

Of course, but I just forgot to write it in my question...
and where does the assertion failure come at?  did you step through the code?
it comes at the fclose(filePointer) in closeSFile. I hope it helps.
Let me guess. The assertion is something like memory is not allocated but freed.
This is because the memory is allocated in the DLL but freed in the EXE. It's not an error but not very nice also.
Avatar of jkr
Regarding the fact that this is the MFC area - is your DLL a MFC DLL? And if so, do you use 'AFX_MANAGE_STATE()' in the functions exported by the DLL?

If not, (and following Mirkwoods idea about memory, which could indeed be the case), try

VD_DLL FILE *openSFile (char *fileName)
{
FILE* fp = fopen (fileName,"w");

setvbuf ( fp, NULL, _IOFBF, 4096); // 4096 is just an example ;-)

return (fp );
}

ASKER CERTIFIED SOLUTION
Avatar of Tommy Hui
Tommy Hui

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks a lot thui!