Обсуждение: CREATE FUNCTION and LANGUAGE 'C'

Поиск
Список
Период
Сортировка

CREATE FUNCTION and LANGUAGE 'C'

От
Céline Rivière
Дата:
Hello,
 
I'm trying to call a C function (C++ in fact but I think, it's not a problem) from a
stored procedure (using CREATE FUNCTION).
 
-------------------------------------------------------
This is the creation of my stored procedure:
 
CREATE FUNCTION Get_Length(TEXT)
RETURNS INTEGER
AS
 '/home/ncxusers/criviere/TOOLS/lib/tools.so', 'Get_Length'
LANGUAGE 'C';
 
This is the C implementation of GetLength :
 
#include <stdio.h>
#include "postgres.h"
#include "fmgr.h"
 
PG_FUNCTION_INFO_V1(file_open);
 
extern "C" Datum file_open (PG_FUNCTION_ARGS)
{
 char *szName = PG_GETARG_CSTRING(0);
 long lgLength = strlen(szName);
 PG_RETURN_UINT32(lgLength);
}
 
 
This is the result of the execution :
 
TestVersioning=# select file_open('abcdefgh') as v_result;
 v_result
----------
        2
(1 row)
-------------------------------------------------------
 
Why does it return 2 and not 8 (length of 'abcdef') ?
 
Thanks for your help.
 
Céline
 
PS:
I think I have a problem with string manipulation.
Because I also have a 2nd issue when trying to return a variable of type TEXT (or VARCHAR).
The following error occurs :
 
pqReadData() -- backend closed the channel unexpectedly.
        This probably means the backend terminated abnormally
        before or while processing the request.
The connection to the server was lost. Attempting reset: Failed
.

Re: CREATE FUNCTION and LANGUAGE 'C'

От
Tom Lane
Дата:
Céline Rivière <cr@fr.netcentrex.net> writes:
> CREATE FUNCTION Get_Length(TEXT)=20
> RETURNS INTEGER
> AS
>  '/home/ncxusers/criviere/TOOLS/lib/tools.so', 'Get_Length'
> LANGUAGE 'C';

> This is the C implementation of GetLength :

> extern "C" Datum file_open (PG_FUNCTION_ARGS)
> {
>  char *szName =3D PG_GETARG_CSTRING(0);
>  long lgLength =3D strlen(szName);

Type TEXT is not the same as a C string.  Look at the builtin functions
that manipulate text arguments.
        regards, tom lane