替换NSAddImage(在GLLoadGen中)

时间:2014-08-01 22:45:56

标签: c macos opengl

使用GLLoadGen生成的GL加载程序包含以下代码:

static void* AppleGLGetProcAddress (const GLubyte *name)
{
  static const struct mach_header* image = NULL;
  NSSymbol symbol;
  char* symbolName;
  if (NULL == image)
  {
    image = NSAddImage("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", NSADDIMAGE_OPTION_RETURN_ON_ERROR);
  }
  /* prepend a '_' for the Unix C symbol mangling convention */
  symbolName = (char*)malloc(strlen((const char*)name) + 2);
  strcpy(symbolName+1, (const char*)name);
  symbolName[0] = '_';
  symbol = NULL;
  /* if (NSIsSymbolNameDefined(symbolName))
     symbol = NSLookupAndBindSymbol(symbolName); */
  symbol = image ? NSLookupSymbolInImage(image, symbolName, NSLOOKUPSYMBOLINIMAGE_OPTION_BIND | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR) : NULL;
  free(symbolName);
  return symbol ? NSAddressOfSymbol(symbol) : NULL;
}

此函数显然加载了OpenGL函数name的地址。但是,自OSX 10.5以来,对NSAddImage and related的调用已被弃用。加载函数地址的当前(不推荐)方法是什么?

1 个答案:

答案 0 :(得分:1)

dlopen()dlsym()和朋友可能是最好的选择。这也将使您的代码更具可移植性,因为它们也适用于大多数Unix系统。

以下是我过去用于在Mac OSX上加载GL功能的一些代码(在版本10.8上测试,对于Mavericks来说仍然可以正常工作):

// Handle to the OpenGL dynlib:
static void * glLibrary;

// Path to GL on OSX. True for version 10.8.
static const char * glLibPath = "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL";

// Loads the OpenGL library:
void LoadGL()
{
    // Load GL dynlib:
    glLibrary = dlopen(glLibPath, RTLD_LAZY);

    if (!glLibrary)
    {
        const char * error = dlerror();
        // handle error
    }
}

// Unloads the GL library:
void UnloadGL()
{
    if (glLibrary)
    {
        if (dlclose(glLibrary) != 0)
        {
            // problem...
        }
        glLibrary = NULL;
    }
}

// Grab a function pointer form the previously loaded GL library:
void * GetGLFunctionPointer(const char * funcName)
{
    assert(funcName != NULL);
    assert(glLibrary != NULL && "OpenGL dynlib not yet loaded!");
    return dlsym(glLibrary, funcName);
}

// Usage example:

int main()
{
    LoadGL();

    void * fn = GetGLFunctionPointer("glEnable");
    assert(fn != NULL);

    UnloadGL();

    return 0;
}