C Stored Functions & The Win32 SDK

Posted: April 28, 2011 in postgresql
Tags: , ,

I recently wanted to build some PostgreSQL C stored functions on a Win32 machine using the Microsoft Windows SDK. I wanted to build with the Microsoft compiler (Visual C) using nmake files, but without involving the Visual Studio IDE.

To do this you need to take your C functions and compile them into a DLL. When you build a DLL with the Microsoft toolchain the functions are not automatically exported from the DLL.

You need to either:

  1. Mark the functions as being exported on the linker command line. This involves listing each exported function on the command line of cl.exe Since I did not try this I’m not going to describe the process
  2. Mark the functions as being exported in the C file by changing the function declaration. Searching the internet I found a few examples of how to do this with the PGDLLEXPORT macro but PostgreSQL kept crashing when it called into my functions built this way.
  3. Create a module definition file as I describe below

Say you have a function

Datum _myFunc(PG_FUNCTION_ARGS);

You then create a module definition file, mymodule.def

Each function that your DLL exports (that would be each function that will be named in a ‘CREATE FUNCTION’ statement) needs to be listed in the .def file under the EXPORTS section.

When linking you would use a command similar to

cl.exe /DEF:mymodule.def /DLL c:\Postgresql\9.0\lib\postgres.lib mymodule.obj

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s