prog.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include <stdio.h>
  2. int func_from_language_runtime(void);
  3. typedef int (*fptr) (void);
  4. #ifdef _WIN32
  5. #include <windows.h>
  6. wchar_t*
  7. win32_get_last_error (void)
  8. {
  9. wchar_t *msg = NULL;
  10. FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER
  11. | FORMAT_MESSAGE_IGNORE_INSERTS
  12. | FORMAT_MESSAGE_FROM_SYSTEM,
  13. NULL, GetLastError (), 0,
  14. (LPWSTR) &msg, 0, NULL);
  15. return msg;
  16. }
  17. int
  18. main (int argc, char **argv)
  19. {
  20. HINSTANCE handle;
  21. fptr importedfunc;
  22. int expected, actual;
  23. int ret = 1;
  24. handle = LoadLibraryA (argv[1]);
  25. if (!handle) {
  26. wchar_t *msg = win32_get_last_error ();
  27. printf ("Could not open %s: %S\n", argv[1], msg);
  28. goto nohandle;
  29. }
  30. importedfunc = (fptr) GetProcAddress (handle, "func");
  31. if (importedfunc == NULL) {
  32. wchar_t *msg = win32_get_last_error ();
  33. printf ("Could not find 'func': %S\n", msg);
  34. goto out;
  35. }
  36. actual = importedfunc ();
  37. expected = func_from_language_runtime ();
  38. if (actual != expected) {
  39. printf ("Got %i instead of %i\n", actual, expected);
  40. goto out;
  41. }
  42. ret = 0;
  43. out:
  44. FreeLibrary (handle);
  45. nohandle:
  46. return ret;
  47. }
  48. #else
  49. #include<dlfcn.h>
  50. #include<assert.h>
  51. int main(int argc, char **argv) {
  52. void *dl;
  53. fptr importedfunc;
  54. int expected, actual;
  55. char *error;
  56. int ret = 1;
  57. dlerror();
  58. dl = dlopen(argv[1], RTLD_LAZY);
  59. error = dlerror();
  60. if(error) {
  61. printf("Could not open %s: %s\n", argv[1], error);
  62. goto nodl;
  63. }
  64. importedfunc = (fptr) dlsym(dl, "func");
  65. if (importedfunc == NULL) {
  66. printf ("Could not find 'func'\n");
  67. goto out;
  68. }
  69. assert(importedfunc != func_from_language_runtime);
  70. actual = (*importedfunc)();
  71. expected = func_from_language_runtime ();
  72. if (actual != expected) {
  73. printf ("Got %i instead of %i\n", actual, expected);
  74. goto out;
  75. }
  76. ret = 0;
  77. out:
  78. dlclose(dl);
  79. nodl:
  80. return ret;
  81. }
  82. #endif