XCForwarder.m 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // XCForwarder.m
  3. // SAGESSE
  4. //
  5. // Created by SAGESSE on 2019/4/30.
  6. //
  7. #import <Foundation/Foundation.h>
  8. /// Declare the initialization method forward.
  9. @interface NSObject (XCForwarder)
  10. +(void*)XCForwarderInit;
  11. @end
  12. /// Init the Forwarder.
  13. static void* forwarder = nil;
  14. __attribute__((constructor)) void XCForwarderInit() {
  15. // printf("%s\n", __func__);
  16. if ([NSObject respondsToSelector:@selector(XCForwarderInit)]) {
  17. forwarder = [NSObject XCForwarderInit];
  18. }
  19. }
  20. /// Load the file from the Forwarder.
  21. unsigned char* XCForwarderLoadData(const char* name, const char* mode, size_t* osize) {
  22. // printf("%s %s - %s\n", __func__, name, mode);
  23. if (forwarder != nil) {
  24. return ((__typeof(&XCForwarderLoadData))forwarder)(name, mode, osize);
  25. }
  26. FILE* fp = fopen(name, mode);
  27. if (fp == nil) {
  28. *osize = 0;
  29. return nil;
  30. }
  31. fseek(fp,0,SEEK_END);
  32. ssize_t size = ftell(fp);
  33. fseek(fp,0,SEEK_SET);
  34. unsigned char* buffer = malloc(size + 1);
  35. size_t readed = fread(buffer, 1, size, fp);
  36. if (readed >= 0) {
  37. buffer[readed] = '\0';
  38. }
  39. *osize = readed;
  40. fclose(fp);
  41. return buffer;
  42. }