开发者

Fatal error when using FILE* in Windows from DLL

开发者 https://www.devze.com 2022-12-29 06:31 出处:网络
Recently, I found a problem with Visual C++ 2008 compiler, but using minor hack avoid it. Currently, I cannot use the same hack, but problem exists as in 2008 as in 2010 (Express).

Recently, I found a problem with Visual C++ 2008 compiler, but using minor hack avoid it. Currently, I cannot use the same hack, but problem exists as in 2008 as in 2010 (Express).

So, I've prepared for you 2 simple C file: one for DLL, one for program:

DLL (file-dll.c):

#include <stdio.h>

__declspec(dllexport) void
print_to_stream (FILE *stream)
{
  fprintf (stream, "OK!\n");
}

And for program, which links this DLL via file-dll.lib:

Program:

#include <stdio.h>

__declspec(dllimport) void print_to_stream (FILE *stream);

int
main (void)
{
  print_to_stream (stdout);
  return 0;
}

To compile and link DLL:

cl /LD开发者_JAVA技巧 file-dll.c

To compile and link program:

cl file-test.c file-dll.lib

When invoking file-test.exe, I got the fatal error (similar to segmentation fault in UNIX).

As I said early, I had that the same problem before: about transferring FILE* pointer to DLL. I thought, that it may be because of compiler mismatch, but now I'm using one compiler for everything and it's not the problem. ;-(

What can I do now?

UPD: I've found solution:

cl /LD /MD file-dll.c
cl /MD file-test.c file-dll.lib

The key is to link to dynamic library, but (I did not know it) by default it links staticaly and (hencefore) error occurs (I see why).

P.S. Thanks for patience.


Potential Errors Passing CRT Objects Across DLL Boundaries

There is a specific example for your situation in here. Depending on how you compile your DLL and program, you might have separate copies of the CRT which will result in an access violation.

0

精彩评论

暂无评论...
验证码 换一张
取 消