咱们知道,PostgreSQL能够支持几乎(这个词彷佛能够不要)全部主流平台,平台间尤为Windows与*nix之间的API差别巨大,PG是怎么作到的呢,用一个简单的例子解释。mysql
前边我写怎么在Windows下编译mysql_fdw提到过的修改:linux
#include "dynloader.h"
mysql_dll_handle = dlopen(_MYSQL_LIBNAME, RTLD_LAZY | RTLD_DEEPBIND); 改成 mysql_dll_handle = dlopen(_MYSQL_LIBNAME, 1);
更正规的写法是sql
#if defined(__APPLE__) || defined(__FreeBSD__) mysql_dll_handle = dlopen(_MYSQL_LIBNAME, RTLD_LAZY); #elif defined WIN32 mysql_dll_handle = pg_dlopen(_MYSQL_LIBNAME, 1); #else mysql_dll_handle = dlopen(_MYSQL_LIBNAME, RTLD_LAZY | RTLD_DEEPBIND); #endif
这里并无修改原有两行,只是为展现应该怎么写,模块代码的跨平台性才会更好些。数据库
dynloader.h在编译前会根据平台指向正确的头文件,在Windows下指向 src/backend/port/dynloader/win32.hbash
#define pg_dlopen(f) dlopen((f), 1) #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror char *dlerror(void); int dlclose(void *handle); void *dlsym(void *handle, const char *symbol); void *dlopen(const char *path, int mode);
Windows下封装了库载入的系列函数,它们实如今 src/backend/port/dynloader/win32.c,节选:ide
void * dlopen(const char *path, int mode) { HMODULE h; int prevmode; /* Disable popup error messages when loading DLLs */ prevmode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); h = LoadLibrary(path); SetErrorMode(prevmode); if (!h) { set_dl_error(); return NULL; } last_dyn_error[0] = 0; return (void *) h; }
最终,仍然是调用传统的Windows函数LoadLibrary。函数
前文还提到修改Solution.pm,只为mysql_fdw添加库和头文件路径,避免影响其余模块。由于mysql有些头文件跟PG定义冲突,你们都是关系数据库,不免有些东西的命名会相同 @_@。.net
上边说的是编译系统自动识别当前平台,编译不一样源文件,*nix平台是在configure脚本里。3d
平台判断:code
case $host_os in aix*) template=aix ;; cygwin*) template=cygwin ;; darwin*) template=darwin ;; dragonfly*) template=netbsd ;; freebsd*) template=freebsd ;; hpux*) template=hpux ;; linux*|gnu*|k*bsd*-gnu) template=linux ;; mingw*) template=win32 ;; netbsd*) template=netbsd ;; openbsd*) template=openbsd ;; solaris*) template=solaris ;; esac
指定软链文件(好比macOS会指向 src/backend/port/dynloader/darwin.h)
"src/include/dynloader.h") CONFIG_LINKS="$CONFIG_LINKS src/include/dynloader.h:src/backend/port/dynloader/${template}.h" ;;
再来看Windows(Solution.pm中),用的是拷贝方式:
if (IsNewer( 'src/include/dynloader.h', 'src/backend/port/dynloader/win32.h')) { copyFile('src/backend/port/dynloader/win32.h', 'src/include/dynloader.h'); }
固然,代码里更多的是传统preprocessor方式:
#ifdef WIN32 /* Win32 does not have UTF-8, so we need to map to UTF-16 */ if (GetDatabaseEncoding() == PG_UTF8 && (!mylocale || mylocale->provider == COLLPROVIDER_LIBC)) { ... #endif /* WIN32 */
我开通了本身的公众号,文章会同步发,欢迎关注。