Thread: Pointers in custom types
Hi, I'm writing a custom type in C that needs to manage two byte arrays (among other things). I have attempted to implement this using something similar to the following struct (along with corresponding input and output functions): typedef struct example { bytea* first; bytea* second; } example; This doesn't seem to work as I was hoping, as I get a segmentation fault upon attempting to insert into a table column of this type (although a cast will work fine). What is the correct way to manage multiple byte arrays within a datatype? Are pointers not usable within a base-type, because of the way Postgres persists them? I guess that the above fails because postgres looks at the size of the struct and simply persists that amount of memory (or VARSIZE if the datatype is a varlena). Is this correct, or should the above work in theory, and there must be a problem in other parts of my implementation? I'm a novice with this stuff, so this is probably a stupid question. If pointers are a no-go, then the only other way I can think of is to maintain one large byte array and an extra index which describes how long the first array is, allowing the second array to be stored directly afterwards. Many thanks for any help, Will.
Will Harrower <wjh105@doc.ic.ac.uk> writes: > I'm writing a custom type in C that needs to manage two byte arrays > (among other things). I have attempted to implement this using something > similar to the following struct (along with corresponding input and > output functions): > typedef struct example { > bytea* first; > bytea* second; > } example; You can't do that; the value of a datatype has to be a single chunk of memory, and it has to be independent of exactly where it's stored because it will get copied around without modification. regards, tom lane
Tom Lane wrote: > Will Harrower <wjh105@doc.ic.ac.uk> writes: > >> I'm writing a custom type in C that needs to manage two byte arrays >> (among other things). I have attempted to implement this using something >> similar to the following struct (along with corresponding input and >> output functions): >> > > >> typedef struct example { >> bytea* first; >> bytea* second; >> } example; >> > > You can't do that; the value of a datatype has to be a single chunk of > memory, and it has to be independent of exactly where it's stored > because it will get copied around without modification. > > regards, tom lane > Ok, that makes sense, thanks. Guess I'll stick to a bytea and an extra index. Cheers, Will.