Prevent name manipulation in C (not C ++) with MinGW to search for dynamic characters

I have a C program where I get function pointers "dynamically" on behalf of a function (that is, I pass the function name as a string and get a pointer to this function). I already do this on Linux using dlopen and dlsym, and I believe that it will work on any other Unix-like with dlfcn .

Problems started when I tried to port this program to Windows using MinGW. When I try to find the name using "GetProcAddress (handle, symbol_name)", where "file_name" is the name of my callback function and "handle" is the handle to the current executable returned by "GetModuleHandle (NULL)", I I get nothing because the name MinGW mangling adds "_" to my symbol name.

The obvious solution (the โ€œ_โ€ prefix for the character I want) seems a bit โ€œdangerousโ€ for portability (can the compiler add two underscores for some of them? I donโ€™t know), so I ask:

  • Is there a better way to prevent the compiler on behalf of my characters? (or a subset of them, only callbacks that I need to find dynamically);

  • Or a way to get GetProcAddress to find them, even when crippled?

I also tried the option - fno-leading-underscore , but it also deleted all external characters, which made the program impossible to communicate with stdlib, etc. (also the warnings in the documentation are a bit scary).

Also note that I use pure C - in any part of my code there is no C ++, and all my code lives in one ".exe".

TIA

+3
source share
2 answers

I donโ€™t know what your problem is, since I cannot reproduce it with the simplest example DLL that I can think of:

/* hello_dll.c */
#include <stdio.h>

__declspec(dllexport) void hello ( void )
{
    puts ( "Hello, DLL!");
}

/* hello_exe.c */
#include <windows.h>
#include <stdio.h>  

int main () {
    typedef void (*pfunc)(void);

    HANDLE hself;

    pfunc hello;

    hself = GetModuleHandle(NULL);

    hello = (pfunc)GetProcAddress(hdll, "hello");

    hello();

    return 0;
}

This is a command line using MinGW gcc without special flags, and it all works:

gcc src\hello_dll.c src\hello_exe.c -o bin\hello.exe
$ bin\hello.exe
Hello, DLL!
$ gcc --version
gcc (GCC) 4.5.0

__declspec(dllexport), ; DLL gcc -shared , , exe.

0

C . , ( ++). , , . ++, , .

, , , .

, ifdefs , .

(Windows Windows API ANSI Unicode, , , .)

, - - C ABI .

0

Source: https://habr.com/ru/post/1791709/


All Articles