Is there a way to obtain, by name, a function at current process in Windows?
c, dll, posix, winapi, windows
Solution
On Windows, executables and DLLs are of the same format (`PE` nowadays), so an executable can export functions too. `GetProcAddress(GetModuleHandle(NULL),TEXT("main_greeting"))` will do what you want if the function is exported from the executable. It's done by `-Wl,-export-all-symbols` for mingw GCC.
I believe there is no equivalent option for Microsoft's linker, so if you use their toolchain, you have to:
- export every function with `__declspec(dllexport)` in source files,
- or write a module definition file listing every exported function, passing it to linker,
- or generate module definition file automatically.
Problem
Is there an equivalent of the following on Windows? ``` #include <dlfcn.h> #include <stdio.h> void main_greeting(void) { printf("%s\n", "hello world"); } void lib_func(void) { void (*greeting)(void) = dlsym(RTLD_MAIN_ONLY, "main_greeting"); greeting ? greeting() : printf("%s\n", dlerror()); } int main(void) { lib_func(); return 0; } ``` This is a short snippet, the real purpose is to call a function know to exist at a main process (`main_greeting`), from inside a function (`lib_func`) from a dynamic loaded library. The main process is not modifiable, and so cannot be rewritten to pass callbacks.