Обсуждение: Getting Text data as C string
Hi.
I wrote a simple c stored procedure that accepts only one text parameter
that i want to convert to a c string.
The problem is that i obtain the C string correctly but with spurious
characters at the end... I use these calls to obtain the c string:
text *t_myfield = PG_GETARG_TEXT_P(0);
char *str_myfield = VARDATA(t_myfield);
Here it is the source:
#include "postgres.h" /* general Postgres declarations */
#include "fmgr.h" /* for argument/result macros */
#include "executor/executor.h" /* for GetAttributeByName() */
#include <math.h>
#include "libpq/pqformat.h" /* needed for send/recv functions */
Datum test_text(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(test_text);
Datum test_text(PG_FUNCTION_ARGS) {
text *t_myfield = PG_GETARG_TEXT_P(0);
char *str_myfield = VARDATA(t_myfield);
elog(NOTICE,"(%s)",str_myfield);
PG_RETURN_TEXT_P(t_myfield);
}
This is the sql to create the function:
CREATE or replace FUNCTION test_text(text)
RETURNS text
AS '/your_path_to_sp.so/sp.so'
LANGUAGE C IMMUTABLE STRICT;
The output is (note the trailing spurious character in the NOTICE line):
NOTICE: (test12345678?)
test_text
--------------
test12345678
I expected:
NOTICE: (test12345678)
test_text
--------------
test12345678
Where is the error?
Thank you,
Denis
Am Montag, 12. März 2007 12:47 schrieb Denis Gasparin: > I wrote a simple c stored procedure that accepts only one text parameter > that i want to convert to a c string. > The problem is that i obtain the C string correctly but with spurious > characters at the end... I use these calls to obtain the c string: The data in a text datum is not null terminated. You need to call the function textout() to convert. Grep the source code for examples of invoking it. -- Peter Eisentraut http://developer.postgresql.org/~petere/
Peter Eisentraut ha scritto:
#define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
#define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
So i can safely use them to obtain a string pointer from a text pointer and viceversa.
I tried and all seemed to work ok.
Thank you,
Denis
I found these defines into the contrib section:Am Montag, 12. März 2007 12:47 schrieb Denis Gasparin:I wrote a simple c stored procedure that accepts only one text parameter that i want to convert to a c string. The problem is that i obtain the C string correctly but with spurious characters at the end... I use these calls to obtain the c string:The data in a text datum is not null terminated. You need to call the function textout() to convert. Grep the source code for examples of invoking it.
#define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
#define GET_TEXT(cstrp) DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
So i can safely use them to obtain a string pointer from a text pointer and viceversa.
I tried and all seemed to work ok.
Thank you,
Denis