跨平台程序中常见的wrapper library
2013-05-17 10:54
113 查看
什么是wrapper?
我在看很多大牛写的程序的时候,发现他们很爱使用wrapper,所以就查来看看。主要还是来自于维基百科。
http://en.wikipedia.org/wiki/Wrapper_library
简介:
In computer programming, a library isa 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.
相关文章推荐
- 常见问题 之 win32平台下用C开发Socket程序
- 如何解决开发x64平台下ASP.NET程序的常见问题
- 微信小程序平台常见拒绝情形
- 请问各位老大,windows平台下用nmake编译的c程序用甚末debug?
- [Image_Codec]常见图片格式的封装及编解码-Android平台(二)PNG
- 读书有感:windows平台一个程序究竟占用多少内存?
- 常见adb程序问题的 trouble shooting
- Vmware Workstation 7利用链接克隆功能创建多程序应用平台
- PHP程序的常见漏洞攻击分析
- 在苹果iOS平台中获取当前程序进程的进程名等信息
- IOS Prefix.pch程序常见文件 的作用
- 100offer 为专业程序打造的招聘平台
- iOS平台内存常见问题
- 怎样做小程序最省钱,小程序开发平台大盘点
- 几个常见的语音交互平台的简介和比较
- 【PHP自学笔记1】如何搭建配置PHP环境、云平台发布、第一个HelloWorld程序
- Android 平台未安装邮件客户端,点击邮件链接,程序崩溃问题
- 使用Gnu gprof进行Linux平台下的程序分析
- Windows平台C++截屏程序