Search code examples
postgresqlvisual-c++postgresql-extensions

How to write a Postgres language handler using MSVC


Here is the code, straight out of the sample. 64 bit install, x64 build.

#include "postgres.h"
#include "executor/spi.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "access/heapam.h"
#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif


PGDLLEXPORT Datum plsample_call_handler(PG_FUNCTION_ARGS); // <-- the answer!!


PG_FUNCTION_INFO_V1(plsample_call_handler);

Datum
plsample_call_handler(PG_FUNCTION_ARGS)
{
  Datum          retval;
  retval = 42;
  return retval;
}

It compiles and links OK. Here is the SQL:

CREATE FUNCTION plsample_call_handler() RETURNS language_handler
    AS 'TryPostgresPl.dll'
    LANGUAGE C;
CREATE LANGUAGE plsample
    HANDLER plsample_call_handler;

And here is the error message.

ERROR: could not find function "plsample_call_handler" in file "C:/Program Files/PostgreSQL/9.5/lib/TryPostgresPl.dll"
SQL state: 42883

So near and yet so far. Really no idea where to look.


Edited to show the answer as per Nick Barnes. Note that a peek with depends.exe showed 2 exports previously, now 3.


Solution

  • The sample in the Postgres docs is squarely targeted at Linux environments; apparently there's a bit more involved in Windows. There is an excellent article by @CraigRinger which explains how to go about it in Visual Studio.

    In this case, it looks like you just need to add the following function prototype:

    PGDLLEXPORT Datum plsample_call_handler(PG_FUNCTION_ARGS);