Home > database >  Why Dll can't export a function with parameter type FILE*
Why Dll can't export a function with parameter type FILE*

Time:04-20

THis is the Dll code

#ifdef HELLO_EXPORTS
#define CLASS_DECLSPEC    __declspec(dllexport)
#else
#define CLASS_DECLSPEC    __declspec(dllimport)
#endif

CLASS_DECLSPEC FILE* GetStdout() {
    return stdout;
}

CLASS_DECLSPEC void dump_code(FILE* fd, const void* data, size_t len)
{
    unsigned char* p = (unsigned char*)data;
    size_t i;
    for(i = 1; i < len   1;   i){
        fprintf(fd, "0x%.2x, ", p[i-1]);
        if((i)==0) fprintf(fd, "\n");
    }
    fprintf(fd, "\n");
}

This is the test code:

#include <stdio.h>
#include <stdlib.h>
#include "dump.h"

int main(){
    char data[] = {
        0x1f,0xc2,0x8b,0x08,0x00,0x00,0x00,0x00,
        0x00,0x00,0x00,0xc3,0x8d,0xc2,0x90,0x3d
    };
    
    dump_code(GetStdout(), data, 16);

    //dump_code(stdout, data, 16);
}

If I directly use stdout: dump_code(stdout, data, 16);, the program will crash in _lock_file. But it will ok to use GetStdout() instead of stdout.

CodePudding user response:

Don't pass FILE * pointers between two copies of libc. You need to link the exe and the dll against the exact same version of libc as a dynamic link library or it won't work.

The general tradition on Windows is don't even try to make this kind of thing work. For every export that would return allocated memory there is another export to free that memory, and more complex things either aren't done at all or done using COM to provide cleanup routines.

OP has now commented that he built with /MTd, which decodes to multi-threaded, static library, and switching to /MDd, which decodes to multi-threaded dll-version-specific library (which is in a .dll) fixed the problem, as expected. When switching to release, /MD must be used instead of /MT or the same problem will reoccur.

  •  Tags:  
  • c dll
  • Related