【问题标题】:Can I boost::bind() to an Objective C function?我可以将::bind() 提升到目标 C 函数吗?
【发布时间】:2009-06-19 21:08:07
【问题描述】:

我不知道这是否可能,但如果是的话,语法会是什么样子?

如果不可能,为什么不呢?

【问题讨论】:

    标签: objective-c boost-bind


    【解决方案1】:

    您应该能够绑定到消息实现 (IMP),它们只是具有两个隐藏参数的普通 C 函数,self_cmd 类型分别为 idSEL

    编辑:刚刚测试了以下完整示例,它似乎可以工作。

    #include <stdio.h>
    #include <boost/bind.hpp>
    #include <Foundation/NSObject.h>
    
    @interface MyClass : NSObject
    {
    }
    -(int) doSomething:(int)arg;
    @end
    
    @implementation MyClass
    -(int) doSomething:(int)arg
    {
      printf("doSomething: self=0x%08x _cmd=0x%08x\n", self, _cmd);
      return arg + 1;
    }
    @end
    
    int main(void)
    {
      MyClass *myObj = [[MyClass alloc] init], *otherObj = [[MyClass alloc] init];
      typedef int (*MyFunc)(id, SEL, int);
      SEL doSomething_sel = @selector(doSomething:);
      MyFunc doSomething_impl = (MyFunc)[myObj methodForSelector:doSomething_sel];
    
      // bind self & _cmd arguments:
      // calls [myObj doSomething:x]
      int result = boost::bind(doSomething_impl, myObj, doSomething_sel, _1)(14);
      printf("result1: %d\n", result);
    
      // bind _cmd & arg:
      // calls [otherObj doSomething:3]
      result = boost::bind(doSomething_impl, _1, doSomething_sel, 42)(otherObj);
      printf("result2: %d\n", result);
    
      return 0;
    }
    

    使用 GNUstep,编译为:

    gcc objcbind.mm -o objcbind -I/usr/include/GNUstep -lobjc -lstdc++ -lgnustep-base
    

    在 Mac OS X 上,编译为:

    gcc objcbind.mm -o objcbind -framework Foundation -lstdc++
    

    输出:

    doSomething:自我=0x01a85f70 _cmd=0x00602220 结果1:15 doSomething:自我=0x01a83d70 _cmd=0x00602220 结果2:43

    【讨论】:

    • 如果其他人看起来像我一样,如果您不想/不需要使用 boost 框架,您也可以使用 std::bind 代替 boost::bind 来实现上述目标。感谢 Adam 提供上述示例!
    • 是的,最好尽可能避免提升。我当时被困在使用它。
    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多