C library Function in Postgresql

Asked

Viewed 77 times

2

I am using Visual Studio 2015 to create a function in a dll, and when I try to use it in Postgres, I get the following message:

server closed the Connection unexpectedly This probably Means the server terminated abnormally before or while Processing the request.

Follows the code:

C:

.c file:

#include<iostream>
#include<math.h>

extern "C" {
#include "postgres.h"
#include "fmgr.h"
#include "sysmoroundtoabnt.h"
#include "utils/builtins.h"
#include "catalog/pg_type.h"
#ifdef PG_MODULE_MAGIC
    PG_MODULE_MAGIC;
#endif
}

PG_FUNCTION_INFO_V1(sysmoroundtoabnt);

Datum
sysmoroundtoabnt(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(10);
    //PG_RETURN_FLOAT8(10);
    //...
}

.h file

#ifndef SYSMOROUNDTOABNT_H
#define SYSMOROUNDTOABNT_H

#include "fmgr.h"

extern "C" __declspec(dllimport) Datum sysmoroundtoabnt(PG_FUNCTION_ARGS);

#endif  

Postgresql:

create or replace function teste_victor( double precision, integer )
returns double precision
as '$libdir/sysmoroundtoabnt', 'sysmoroundtoabnt' language C;

SQL Command

select teste_victor(0.015, -2)

PS.: If I change the code in C, to return PG_RETURN_FLOAT8(10), the error becomes this:

invalid memory alloc request size 4294967290

Another important information, is that the error only happens in Windows. For Linux works perfectly, just need to remove the extern of the archives .c and .h

What’s wrong with my code?

1 answer

0


To solve the problem:

  1. Remove extern "C" of the archives;
  2. Place PGDLLEXPORT Datum sysmoroundtoabnt(PG_FUNCTION_ARGS) in the file . h;
  3. Change the Double for Float8 and Int for Int32 in the file . c;

I believe the main problem was the way I was exposing my method. The crash on Postgres was due to memory overuse, which was caused when using native types instead of those suggested by the postgres documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.