Returning bigint from C extension

Started by Jason Armstrongover 16 years ago2 messagesgeneral
Jump to latest
#1Jason Armstrong
ja@riverdrums.com

How can I return a bigint value from a C extension function?

I have a table with a bytea column:

CREATE TABLE mydata(data bytea);

I would like to select and index based on a subset of the data:

CREATE FUNCTION get_key(bytea) returns BIGINT AS '/lib/data.so'
LANGUAGE C IMMUTABLE;
CREATE INDEX mydata_key_idx on mydata(get_key(data));

# SELECT get_key(data) FROM mydata;

My code :

PG_FUNCTION_INFO_V1(get_key);
Datum get_key(PG_FUNCTION_ARGS)
{
bytea *val;
unsigned int len;
long long res;

val = PG_GETARG_BYTEA_P(0);
len = VARSIZE(val) - VARHDRSZ;
res = _extract_key(VARDATA(val), len);
PG_FREE_IF_COPY(val, 0);

PG_RETURN_INT32(res);
}

The PG_RETURN_INT32() macro causes the server to terminate.

It works if I convert to a cstring:

char *result = palloc(32);
snprintf(result, 32, "%lld", res);
PG_RETURN_CSTRING(result);

But then I can't index it, or sort on it either.

(And, as a side note, is the above code the correct way to use bytea
data from C?)

Regards,

--
Jason Armstrong

#2Martijn van Oosterhout
kleptog@svana.org
In reply to: Jason Armstrong (#1)
Re: Returning bigint from C extension

On Mon, Nov 23, 2009 at 09:58:21AM +0200, Jason Armstrong wrote:

How can I return a bigint value from a C extension function?

I have a table with a bytea column:

CREATE TABLE mydata(data bytea);

I would like to select and index based on a subset of the data:

CREATE FUNCTION get_key(bytea) returns BIGINT AS '/lib/data.so'
LANGUAGE C IMMUTABLE;
CREATE INDEX mydata_key_idx on mydata(get_key(data));

For a bigint you need to use the right return type: PG_RETURN_INT64()

(And, as a side note, is the above code the correct way to use bytea
data from C?)

Looks ok.

Have a nice day,
--
Martijn van Oosterhout <kleptog@svana.org> http://svana.org/kleptog/

Show quoted text

Please line up in a tree and maintain the heap invariant while
boarding. Thank you for flying nlogn airlines.