Re: Weird problems with C extension and bytea as input type - Mailing list pgsql-general

From David W Noon
Subject Re: Weird problems with C extension and bytea as input type
Date
Msg-id 20110322222155.30d8cab6@karnak.local
Whole thread Raw
In response to Re: Weird problems with C extension and bytea as input type  (Merlin Moncure <mmoncure@gmail.com>)
Responses Re: Weird problems with C extension and bytea as input type  (Adrian Schreyer <ams214@cam.ac.uk>)
Re: Weird problems with C extension and bytea as input type  (Adrian Schreyer <adrian@schreyer.me>)
List pgsql-general
On Tue, 22 Mar 2011 16:14:47 -0500, Merlin Moncure wrote about Re:
[GENERAL] Weird problems with C extension and bytea as input type:

[snip]
>>> On Tue, Mar 22, 2011 at 8:22 AM, Adrian Schreyer <ams214@cam.ac.uk>
>>> wrote:
[snip]
>>>> bytea *b = PG_GETARG_BYTEA_P(0);
>>>> char *ism;
>>>>
>>>> ism = function(b);
>>>>
>>>> PG_RETURN_CSTRING(ism);

What is the prototype for function()?  If it returns a char * then you
will likely have either scope problems, reentrancy problems or memory
leaks. If you are going to buy the C++ religion then you usually need to
buy it wholesale: do all if your string processing as std::string
objects and only return to char * when you revert to C.

As a rough example:

  bytea *b = PG_GETARG_BYTEA_P(0);
  std::string ism;

  ism = function(std::string(VARDATA(b), VARSIZE(b)-VARHDRSZ));

  PG_RETURN_CSTRING(ism.c_str());

Note that this returns an ASCIIZ string, which is not necessarily the
same as the C++ string.  You would be better off creating a
PostgreSQL text object and then return that.

>Well, C++ string constructor is proper in the sense it makes copy of
>the source data.  however, it's a little weird that you are passing
>bytea like this...bytea can contain null and c++ string initialization
>stops at any 0 byte.

Not so.  If the constructor also specifies a length then the data
pointer's area is not assumed to be NUL-terminated.

>Maybe you should be encoding the data to text (say, to hex) first?

Better to use the supplied length in the varlena descriptor.
--
Regards,

Dave  [RLU #314465]
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
dwnoon@ntlworld.com (David W Noon)
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Attachment

pgsql-general by date:

Previous
From: "Andy Chambers"
Date:
Subject: Trigger Function return values
Next
From: Scott Ribe
Date:
Subject: Re: Trigger Function return values