如何通过名称获取 "extern const int" 值

How to get an "extern const int" value by its name

我想通过名称获取 extern constint 值。

例如在我的 .h 文件中:

extern const int MY_INT_CONST;

在我的 .m 文件中:

const int MY_INT_CONST = 0;

我想要的:

- (void) method {
    int i = [getMyConstantFromString:@"MY_INT_CONST"];
}

我该怎么做?

我在 RunTime 中搜索 api 但我没有找到任何东西。

不需要 [getMyConstantFromString:@"MY_INT_CONST"];

直接使用如下

- (void) method {
    int i = MY_INT_CONST;
}

没有简单的方法可以做到这一点。语言和运行时都没有为此提供便利。

可以使用动态加载器的 API 通过名称查找符号的地址。

// Near top of file
#include <dlfcn.h>

// elsewhere
int* pointer = dlsym(RTLD_SELF, "MY_INT_CONST");
if (pointer)
{
    int value = *pointer;
    // use value...
}

请注意,这是传递给 dlsym() 的 C 风格字符串。如果你有一个 NSString,你可以使用 -UTF8String 来得到一个 C 风格的字符串。