跨平台程序中常见的wrapper library

什么是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.

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值