module.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #if defined _WIN32 || defined __CYGWIN__
  2. #define DLL_PUBLIC __declspec(dllexport)
  3. #else
  4. #if defined __GNUC__
  5. #define DLL_PUBLIC __attribute__ ((visibility("default")))
  6. #else
  7. #pragma message ("Compiler does not support symbol visibility.")
  8. #define DLL_PUBLIC
  9. #endif
  10. #endif
  11. #if defined(_WIN32) || defined(__CYGWIN__)
  12. #include <stdio.h>
  13. typedef int (*fptr) (void);
  14. #ifdef __CYGWIN__
  15. #include <dlfcn.h>
  16. fptr find_any_f (const char *name) {
  17. return (fptr) dlsym(RTLD_DEFAULT, name);
  18. }
  19. #else /* _WIN32 */
  20. #include <windows.h>
  21. #include <tlhelp32.h>
  22. /* Unlike Linux and OS X, when a library is loaded, all the symbols aren't
  23. * loaded into a single namespace. You must fetch the symbol by iterating over
  24. * all loaded modules. Code for finding the function from any of the loaded
  25. * modules is taken from gmodule.c in glib */
  26. fptr find_any_f (const char *name) {
  27. fptr f;
  28. HANDLE snapshot;
  29. MODULEENTRY32 me32;
  30. snapshot = CreateToolhelp32Snapshot (TH32CS_SNAPMODULE, 0);
  31. if (snapshot == (HANDLE) -1) {
  32. printf("Could not get snapshot\n");
  33. return 0;
  34. }
  35. me32.dwSize = sizeof (me32);
  36. f = NULL;
  37. if (Module32First (snapshot, &me32)) {
  38. do {
  39. if ((f = (fptr) GetProcAddress (me32.hModule, name)) != NULL)
  40. break;
  41. } while (Module32Next (snapshot, &me32));
  42. }
  43. CloseHandle (snapshot);
  44. return f;
  45. }
  46. #endif
  47. int DLL_PUBLIC func() {
  48. fptr f;
  49. f = find_any_f ("func_from_language_runtime");
  50. if (f != NULL)
  51. return f();
  52. printf ("Could not find function\n");
  53. return 1;
  54. }
  55. #else
  56. /*
  57. * Shared modules often have references to symbols that are not defined
  58. * at link time, but which will be provided from deps of the executable that
  59. * dlopens it. We need to make sure that this works, i.e. that we do
  60. * not pass -Wl,--no-undefined when linking modules.
  61. */
  62. int func_from_language_runtime();
  63. int DLL_PUBLIC func(void) {
  64. return func_from_language_runtime();
  65. }
  66. #endif