I'm trying to write the following c code in postgres c function style - The argument passed is a value of a table column of type varchar, Needed some help to map this pure C code in the postgres C format of the type -
Datum func_name (PG_FUNCTION_ARGS)
Can somebody please help to map this and return the appropriate char value?
static uint32_t key = 0xOQ9426YP;
uint32_t tmpKey = 0x00000000;
int i = 0;
uint32_t *in = (uint32_t *) str;
uint32_t *out = (uint32_t *) malloc (256);
memset (out, 0, 256);
tmpKey = key;
for (i = 0; i < (256/sizeof (uint32_t)); i++)
{
out[i] = tmpKey ^ in[i];
tmpKey = out[i];
}
memcpy (output, (char *) out, 256);
Thanks & Regards, VJ
For data PostgreSQL uses own internal format and structures that should not be compatible with C language. For strings a varlena
format is used - in this format first N bytes are encoded length - and after these bytes are encoded data. The direct access is not recommended - for almost all work there are a macros.
For example - some small function hello
can looks like:
Datum
Hello(PG_FUNCTION_ARGS)
{
text *txt = PG_GETARG_TEXT_PP(0);
text *result;
char *str;
char *hello = "Hello, ";
int size;
int hello_size;
-- conversion to c string
str = text_to_cstring(txt);
-- show it on debug console
elog(NOTICE, "input string: %s", str);
hello_size = strlen(hello);
size = hello_size + VARSIZE_ANY_EXHDR(txt) + VARHDRSZ;
-- allocate memory for result, use palloc, not malloc!
result = palloc(size);
--set size of result varlena type
SET_VARSIZE(result, size);
-- set data
memcpy(VARDATA(result), str, hello_size);
memcpy(VARDATA(result) + hello_size,
VARDATA_ANY(txt), VARSIZE_ANY_EXHDR(txt));
-- returns data
PG_RETURN_TEXT_P(result);
}
You can see, this is C and it is not C. There are lot of macros, than can be used a) for portability purposes, b) for hiding complexity. It is good to start to read documentation or some presentation.
This topic is not too hard or too complex, but it is not intuitive - you cannot to start without reading documentation.
User contributions licensed under CC BY-SA 3.0