3

我进口:

#import <sys/types.h>
#import <sys/sysctl.h>

sysctlbyname("hw.machine", NULL, &size, NULL, 0);当我在外部使用该函数时,dispatch_once编译器在 . 当我在第二个参数的块内使用它时dispatch_once,我收到此错误:

No matching function for call to 'sysctlbyname'

这是完整的代码:

#import <sys/types.h>
#import <sys/sysctl.h>

NSString *GetMachineName(void) {
  static NSString *machine = nil;

  if (nil == machine) {
    size_t size;

    sysctlbyname("hw.machine", NULL, &size, NULL, 0); // DEFINED IN SYSCTL.H


    static dispatch_once_t once;
    dispatch_once(&once, ^ {
      // Set 'oldp' parameter to NULL to get the size of the data
      // returned so we can allocate appropriate amount of space
      sysctlbyname("hw.machine", NULL, &size, NULL, 0); // DEFINED IN SYSCTL.H

      // Allocate the space to store name
      char *name = (char *)malloc(size);

      // Get the platform name
      sysctlbyname("hw.machine", name, &size, NULL, 0);

      // Place name into a string
      machine = [NSString stringWithCString:name encoding:NSASCIIStringEncoding];

      // Done with this
      free(name);
    });

    if ([machine isEqualToString:@"iPhone1,1"]) return IPHONE_1G_PLATFORM;
    if ([machine isEqualToString:@"iPhone1,2"]) return IPHONE_3G_PLATFORM;
    if ([machine isEqualToString:@"iPhone2,1"]) return IPHONE_3GS_PLATFORM;
    if ([machine isEqualToString:@"iPhone3,1"]) return IPHONE_4G_PLATFORM;
    if ([machine isEqualToString:@"iPod1,1"]) return IPOD_1G_PLATFORM;
    if ([machine isEqualToString:@"iPod2,1"]) return IPOD_2G_PLATFORM;
    if ([machine isEqualToString:@"iPod3,1"]) return IPOD_3G_PLATFORM;
    if ([machine isEqualToString:@"iPad1,1"]) return IPAD_1G_PLATFORM;
    if ([machine isEqualToString:@"iPad2,1"]) return IPAD_2G_PLATFORM;
    if ([machine isEqualToString:@"i386"] || [machine isEqualToString:@"x86_64"]) return SIMULATOR_PLATFORM;
    return NULL;
  }

  return machine;
}
4

1 回答 1

1

为了解决这个问题,我需要将声明size放在块内,因为事实上,参数没有用 装饰__block,所以它编译为 a const,与 . 的参数列表不匹配sysctlbyname。由于函数重载,编译器发现该函数不存在。

TLDR:编译器认为我使用的函数是

int sysctlbyname(const char *, void *, const size_t*, void *, size_t);

而不是

int sysctlbyname(const char *, void *, *size_t, void *, size_t);
于 2013-01-25T19:30:35.190 回答