Thread: C text to string issue

C text to string issue

From
"Sam Stephens"
Date:
Hiya, I'm trying to write a function that takes a text argument as input, and converts it to a C 
string to then use for file I/O.

However it crashes my postgres when it gets to the memcpy line (e.g. you get the Test A 
notice and the Test B notice, but not the Test C notice)

The odd thing is my code is now based on genfile.c and I cannot see what I'm doing 
differently/wrong.

http://cvs.pgadmin.org/cgi-bin/viewcvs.cgi/pgadmin-tools/support/genfile.c?rev=HEAD

I compile using the commands 

gcc -c qpsolve.c -I/usr/src/postgresql-7.4.2/src/include
gcc -shared -o qpsolve.so qpsolve.o
cp qpsolve.so /usr/local/pgsql/lib -f

My command to create the function is 

CREATE OR REPLACE FUNCTION F_QPSOLVE(text) RETURNS text
AS 'qpsolve.so'
LANGUAGE 'C' WITH (isStrict);

This is my source code, qpsolve.c

****

#include "postgres.h"
#include "fmgr.h"

/* Routine to write session variables */

PG_FUNCTION_INFO_V1(f_qpsolve);

text * f_qpsolve(text *arg)
{char *filename;
int len=VARSIZE(arg)-VARHDRSZ;elog(NOTICE, "test A");
filename = palloc(len+1);
elog(NOTICE, "test B");memcpy(filename,VARDATA(arg), len);
elog(NOTICE, "test C");
filename[len]=0;
elog(NOTICE, filename);
return 0;
}

****

Your help solving this would be much appreciated.

All the best,Sam



Re: C text to string issue

From
Tom Lane
Date:
"Sam Stephens" <tangent@inspire.net.nz> writes:
> PG_FUNCTION_INFO_V1(f_qpsolve);

> text * f_qpsolve(text *arg)
> {

This function is not written according to the V1 calling convention.
Either rewrite it or remove the INFO_V1 macro.

>     return 0;

You most certainly do not want to return a null "text *" pointer.
        regards, tom lane