Re: C Extension woes - Mailing list pgsql-hackers

From Jan Urbański
Subject Re: C Extension woes
Date
Msg-id 48A2C301.5050102@students.mimuw.edu.pl
Whole thread Raw
In response to C Extension woes  (Tim Hawes <thawes@novadine.com>)
List pgsql-hackers
Tim Hawes wrote:
> Hello all,
> 
> I am trying to write an extension in C that returns a simple environment 
> variable. The code compiles without any complaint or warning, and it 
> loads fine into the database, however, when I run the function, I get 
> disconnected from the server.
> 
> Here is my C code:
> 
> #include <postgres.h>
> #include <fmgr.h>
> PG_MODULE_MAGIC;
> 
> #include <stdio.h>
> #include <stdlib.h>
> 
> PG_FUNCTION_INFO_V1(pl_masterkey);
> 
> text * pl_masterkey(PG_FUNCTION_ARGS)
> {
>  char *e_var = getenv("PGMASTERKEY");
>  size_t length = VARSIZE(e_var) - VARHDRSZ;
> 
>  text * mkey = (text *) palloc(length);
>  VARATT_SIZEP(mkey) = length;
>  memcpy(VARDATA(mkey), e_var, length);
> 
>  return mkey;
> }

Oh, you confused a lot of things.
You need something like

Datum pl_masterkey(PG_FUNCTION_ARGS) {  char *e_var = getenv("PGMASTERKEY");
PG_RETURN_TEXT_P(cstring_to_text(e_var));
}

You don't need to mess with anything varlena-related (liek VARSIZE), 
it's all handled for you.
Also, read up on how to declare user-defined C functions in Postgres 
(they always need to return Datum).

Cheers,
Jan

-- 
Jan Urbanski
GPG key ID: E583D7D2

ouden estin


pgsql-hackers by date:

Previous
From: Tim Hawes
Date:
Subject: C Extension woes
Next
From: Magnus Hagander
Date:
Subject: Re: Replay attack of query cancel