Wrapper libraries (orlibrary wrappers) consist of a thin layer of code (a "shim") which translates alibrary's existing interface into a compatible interface. This is done for several reasons:
Wrapper libraries can be implemented using theadapter,façade, and to a lesser extent,proxydesign patterns.
The specific way in which a wrapper library is implemented is highly specific to the environment it is being written in and the scenarios which it intends to address. This is especially true in the case whencross-language/runtime interoperability is a consideration.
The following provides a general illustration of a common wrapper library implementation over aC POSIX library header<pthread.h> (for POSIX threads, or "pthreads"). In this example, aC++ interface acts as a "wrapper" around aC interface.
In<pthread.h>:
#include<sys/types.h>// previous declarations...intpthread_mutex_init(pthread_mutex_t*mutex,constpthread_mutexattr_t*attr);intpthread_mutex_destroy(pthread_mutex_t*mutex);intpthread_mutex_lock(pthread_mutex_t*mutex);intpthread_mutex_unlock(pthread_mutex_t*mutex);// more functions...
Wrapping<pthread.h> withPosixThread.cppm:
exportmoduleorg.posix.PosixThread;import<pthread.h>;exportnamespaceorg::posix{// previous wrappers...classThreadMutex{private:::pthread_mutex_tmutex;friendclassThreadLock;voidlock()noexcept{::pthread_mutex_lock(&mutex);}voidunlock()noexcept{::pthread_mutex_unlock(&mutex);}public:ThreadMutex(){::pthread_mutex_init(&mutex,0);}~ThreadMutex(){::pthread_mutex_destroy(&mutex);}};classThreadLock{private:ThreadMutex&mutex;public:explicitThreadLock(ThreadMutex&mutex):mutex{mutex}{mutex.lock();}~ThreadLock(){mutex.unlock();}};// more wrappers...}
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 utilizesresource acquisition is initialization (RAII) in the neworg::posix::ThreadMutex andorg::posix::ThreadLock classes to ensureorg::posix::ThreadMutexs are eventually unlocked andpthread_mutex_t objects are automatically released.
The above code closely mimics the implementation ofboost::scoped_lock andboost::mutex classes fromBoost which are part of theBoost.Thread library.
Some wrapper libraries exist to act as a bridge between a client application and a library written using an incompatible technology. For instance, aJava application may need to execute asystem call. However system calls are typically exposed as C library functions. To resolve this issue Java implements wrapper libraries which make these system calls callable from a Java application.
In order to achieve this, languages like Java provide a mechanism calledforeign function interface that makes this possible. Some examples of these mechanisms include:
std::ffi (Rust)Some examples of existing wrapper libraries: