Victor Zanella Victor Zanella - 2 months ago 13
C Question

C library function in Postgresql

I'm using Visual Studio 2015 to build a postgres function and I get this message when I try to use my function:


server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.


Here is my 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 C code to return PG_RETURN_FLOAT8(10), i get thi error:


invalid memory alloc request size 4294967290


What is wrong with my code ?

Answer

To solve the problem:

  1. Remove extern "C" of both file;
  2. Put PGDLLEXPORT Datum sysmoroundtoabnt(PG_FUNCTION_ARGS) on .h file;
  3. Change Double to Float8 and Int to Int32 on .c File;

I guess the main problem was how I was expounding my function.

Comments