您的位置:首页 > 移动开发

跨平台程序中常见的wrapper library

2013-05-17 10:54 113 查看

什么是wrapper?

我在看很多大牛写的程序的时候,发现他们很爱使用wrapper,所以就查来看看。

主要还是来自于维基百科。

http://en.wikipedia.org/wiki/Wrapper_library

简介:

In computer programming, a library is
a collection of subroutines or classes used to develop software. Libraries expose interfaces which clients of the library use to execute library routines. Wrapper libraries (or library wrappers) consist of a thin
layer of code which translates a library's existing interface into a compatible interface. This is done for several reasons:

To refine a poorly designed or complicated interface.
Allow code to work together which otherwise cannot (e.g. Incompatible data formats).
Enable cross language and/or runtime interoperability.

也就是说wrapper library是对现有程序的包装,让它的兼容性更好。由于有的时候程序员在写程序的时候只是注意到了完成功能,而导致程序接口的定义复杂,或者由于采取了不同的编程语言,或者不同的数据格式造成的兼容性问题。

wiki上举了一个很好的例子。

例子:

Example [edit]

The following provides a general illustration of a common wrapper library implementation. In this example, a C++ interface acts as a "wrapper" around a C-language interface.

C interface [edit]

int pthread_mutex_init(pthread_mutex_t * mutex , pthread_mutexattr_t * attr);
int pthread_mutex_destroy (pthread_mutex_t * mutex);
int pthread_mutex_lock (pthread_mutex_t * mutex );
int pthread_mutex_unlock (pthread_mutex_t * mutex );


C++ wrapper [edit]

class Mutex
{
pthread_mutex_t mutex;

public:

Mutex()
{
pthread_mutex_init(&mutex, 0);
}

~Mutex()
{
pthread_mutex_destroy(&mutex);
}

private:

friend class Lock;

void lock()
{
pthread_mutex_lock(&mutex);
}

void unlock()
{
pthread_mutex_unlock(&mutex);
}
};

class Lock
{
Mutex& mutex;
public:
Lock(Mutex& mutex):mutex(mutex){mutex.lock();}
~Lock(){mutex.unlock();}
};


The original C-interface can be regarded as error prone, particularly in the case where users of the library forget to unlock an already locked mutex. The new interface effectively utilizes RAII
(Resource Acquisition is Initialization) in the new Mutex and Lock classes to ensure Mutexs
are eventually unlocked and pthread_mutex_t objects are automatically released.

上面用C写的程序提供的函数接口是很容易导致错误的,最简单的例子就是忘了初始化init和用完了destroy,下面的C++程序对这样的操作做了封装,使得在初始化对象和销毁对象的时候都自动调用了相应的c函数接口。

The above code closely mimics the implementation of boost::scoped_lock and boost::mutex which are part of the boost::thread library.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: