boost::bind And Objective-C

http://stackoverflow.com/questions/1020028/can-i-boostbind-to-an-objective-c-function


You should be able to bind to a message implementation (IMP), which are just plain C functions with two hidden parameters, self and _cmd of types id and SEL respectively.

EDIT: Just tested the following complete example, and it appears to work.

#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;
}



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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值