0

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

2
  • This code completely ignores endianness. Is that your intention? Commented Nov 22, 2018 at 4:24
  • On top of that, 0xOQ9426YP is not a valid hexadecimal literal. Commented Nov 22, 2018 at 4:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.