欺骗编译器取得ISurface对象的方法

欺骗编译器取得ISurface对象的方法

我们在使用Android NDK的Surface的时候,遇到无法得到ISurface对象的问题,描述如下:

Surface类的定义如下:

class Surface
: public EGLNativeBase
{
public:
...

private:
// can't be copied
...

friend class SurfaceComposerClient;
friend class SurfaceControl;

// camera and camcorder need access to the ISurface binder interface for preview
friend class Camera;
friend class MediaRecorder;
// mediaplayer needs access to ISurface for display
friend class MediaPlayer;
friend class IOMX;
// this is just to be able to write some unit tests
friend class Test;

sp getClient() const;
sp getISurface() const;
...
}

注意看,如果我们要得到ISurface对象,必须调用getISurface函数,可是这个函数在类定义里是private的,
外部无法访问。
另还注意到,这里定义了一堆的友元类,从语法上讲,友元类是可以访问Surface的私有成员的,因此可以想
个方法来欺骗编译器,如下:

我们定义了一个类,按照上面的提示,取名字叫Test,这是关键

// 这个类纯粹是为了取得ISurface对象,
// 因为在Surface里,要取得ISurface对象,必须是友元类,
// 因此在这里按Surface类的定义,假造了一个友元类来欺骗编译器
namespace android {
class Test {
public:
static sp & getISurface(const sp &surface)
{
return surface->mSurface;
}
};
};

这样,我们可以用下面的语句来获取ISurface对象
// 这一句需要权限,要在surface.h里加入frends class
isurface = Test::getISurface(surface);

这里还有一个提示,一个类的成员,是私有还是公有,是编译器来检查的,是在编译的时候检查的,
在编译完成后,二进制代码里,就没有这个区别了,可以随便访问。

http://blog.sina.com.cn/s/blog_53d1e55b0100ne50.html

原文地址:https://www.cnblogs.com/eustoma/p/2415845.html