可可检查函数是否存在 [英] Cocoa check if function exists

查看:120
本文介绍了可可检查函数是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用仅在OS X 10.9上可用的函数,但不能使用10.9 SDK编译。这是可能的吗?



我试过弱链接,但编译器只是给出一个错误,函数未定义。


<假设你正在谈论一个C函数,你可以使用 dlopen 函数来完成这项工作:

  #include< dlfcn.h> 

int main(){
void * lib = dlopen(/ System / Library / Frameworks / ApplicationServices.framework / ApplicationServices,RTLD_LAZY);
void * function = dlsym(lib,CGColorGetConstantColor);

//将函数转换为正确的格式
CGColorRef(* dynamic_getConstantColor)(CFStringRef colorName)= function;

NSLog(@%@,dynamic_getConstantColor(CFSTR(kCGColorBlack)));

dlclose(lib);
}

输出:

 
2013-06-20 12:43:13.510 TestProj [1699:303] [(kCGColorSpaceICCBased; kCGColorSpaceModelMonochrome; Generic Grey Profile)](0 1)


$ b

将会打破iOS上的沙盒限制,Mac也最有可能。这是你为链接器付出的价格。


I'd like to use a function that's only available on OS X 10.9, but WITHOUT compiling with the 10.9 SDK. Is that possible?

I've tried weak linking, but the compiler just gives out an error that the function is not defined.

解决方案

Assuming you are talking about a C function, you can do this with the dlopen function:

#include <dlfcn.h>

int main() {
    void *lib = dlopen("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices", RTLD_LAZY);
    void *function = dlsym(lib, "CGColorGetConstantColor");

    // cast the function to the right format
    CGColorRef (*dynamic_getConstantColor)(CFStringRef colorName) = function;

    NSLog(@"%@", dynamic_getConstantColor(CFSTR("kCGColorBlack")));

    dlclose(lib);
}

Output:

2013-06-20 12:43:13.510 TestProj[1699:303]  [ (kCGColorSpaceICCBased; kCGColorSpaceModelMonochrome; Generic Gray Profile)] ( 0 1 )

You will need to figure out the dylib in which the function you want resides, first, though.

This will break the sandbox limitations on iOS, and Mac most likely as well. It is the price you pay for trying to get around the linker.

这篇关于可可检查函数是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆