引言:
使用C语言写PostgreSQL中的函数可以很方便的扩展PostgreSQL数据库的功能。由C语言写的函数,使用方法与PostgreSQL中内置的函数基本没有差别,性能基本也没有什么差别。本文一步一步教你如何使用C语言写PostgreSQL函数:
1. 先根据一个简单函数的生成一个动态库,看PostgreSQL能否使用
源文件为cfunc.c,内容如下:
#include "postgres.h"
int add_one(int arg)
{
return arg + 1;
}
然后我们编译生成cfunc.so,并把此文件拷贝到PostgreSQL的库路径下:
gcc -I`pg_config --includedir-server` -c cfunc.c
gcc -shared -o cfunc.so cfunc.o
cp cfunc.so `pg_config --libdir`/.
我们来测试一下:
osdba@osdba-laptop:~/src/ctest/pgfunc$ psql
psql (9.3.2)
Type "help" for help.
osdba=# load 'cfunc.so';
ERROR: incompatible library "/home/osdba/pgsql9.3.2/lib/cfunc.so": missing magic block HINT: Extension libraries are required to use the PG_MODULE_M