interface_cast<ICameraService>(binder) : 其中binder 为IBinder类型,实际为BpBinder
interface_cast 定义在IInterface.h文件中,以下:
声明以下:android
#define DECLARE_META_INTERFACE(INTERFACE) \
static const android::String16 descriptor; \
static android::sp<I##INTERFACE> asInterface( \
const android::sp<android::IBinder>& obj); \
virtual const android::String16& getInterfaceDescriptor() const; \
I##INTERFACE(); \
virtual ~I##INTERFACE(); \this
定义以下:spa
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \
android::sp<I##INTERFACE> I##INTERFACE::asInterface( \
const android::sp<android::IBinder>& obj) \
{ \
android::sp<I##INTERFACE> intr; \
if (obj != NULL) { \
intr = static_cast<I##INTERFACE*>( \
obj->queryLocalInterface( \
I##INTERFACE::descriptor).get()); \
if (intr == NULL) { \
intr = new Bp##INTERFACE(obj); \
} \
} \
return intr; \
} \
code
见代码:intr = new Bp##INTERFACE(obj), 这里INTERFACE为ICameraService, 即new BpCameraService(obj);对象
frameworks/av/camera/ICameraService.h 中BpCameraService的定义blog
BpCameraService(const sp<IBinder>& impl)
: BpInterface<ICameraService>(impl)
{
}继承
BpInterface(impl), 将BpBinder传递给了BpInterface, 再看:ip
frameworks/native/include/IInterface.h 中BpInterface的实现(这里实现也放在头文件了)rem
template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
: BpRefBase(remote)
{
}get
BpRefBase(remote),将BpBinder 又传递给了BpRefBase中,继续跟进
frameworks/native/libs/binder/Binder.cpp 中看BpRefBase的实现
BpRefBase::BpRefBase(const sp<IBinder>& o)
: mRemote(o.get()), mRefs(NULL), mState(0)
{
extendObjectLifetime(OBJECT_LIFETIME_WEAK);
if (mRemote) {
mRemote->incStrong(this); // Removed on first IncStrong().
mRefs = mRemote->createWeak(this); // Held for our entire lifetime.
}
}
mRemote(o.get()), 这里将BpBinder 保存在了BpRefBase中的变量mRemote中
又有BpCameraService 继承 BpInterface 继承 BpRefBase 继承 RefBase,因此 interface_cast 其实是建立了一个BpCameraService对象,而且将BpBinder复制给它的祖先类