简体   繁体   中英

How do you return a bit(n) or bit varying(n) field in a C-language function for Postgres?

Question says it all; how do I have a C-language function for Postgres return a bitstring?

Extending Nick's (very helpful!) comment, here is a simple example and the return result in Postgres (Postgres.app 9.4, OS X Yosemite):

#include <postgres.h>
#include <utils/array.h>
#include <utils/varbit.h>
#include <fmgr.h>
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
Datum pg_test_varbit(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_test_varbit);
Datum
pg_test_varbit(PG_FUNCTION_ARGS)
{
    VarBit  *result;
    int len, rlen;

    len             = 16;
    rlen            = VARBITTOTALLEN(len);
    result          = palloc0(rlen);
    SET_VARSIZE(result, rlen);
    VARBITLEN(result)
                    = len;

    VARBITS(result)[0] = 0xFF;
    VARBITS(result)[1] = 0x0;

    PG_RETURN_VARBIT_P(result);
}

Once compiled/installed, I ran in a Postgres shell:

DROP FUNCTION IF EXISTS pg_test_varbit();
CREATE OR REPLACE FUNCTION pg_test_varbit() RETURNS varbit
  AS 'pgtestvarbit', 'pg_test_varbit'
  LANGUAGE C STRICT;

SELECT pg_test_varbit();

and received "1111111100000000" as the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM