我在C:
中实现了以下存储过程extern "C" DLLEXPORT Datum
selectServeralRows(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
int call_cntr;
int max_calls;
TupleDesc tupdesc;
AttInMetadata *attinmeta;
/* stuff done only on the first call of the function */
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
/* create a function context for cross-call persistence */
funcctx = SRF_FIRSTCALL_INIT();
/* switch to memory context appropriate for multiple function calls */
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* total number of tuples to be returned */
funcctx->max_calls = 1;
/* Build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
/*
* generate attribute metadata needed later to produce tuples from raw
* C strings
*/
attinmeta = TupleDescGetAttInMetadata(tupdesc);
funcctx->attinmeta = attinmeta;
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
if (funcctx->call_cntr < funcctx->max_calls) /* do when there is more left to send */
{
Datum* val = (Datum*)palloc(2 * sizeof(Datum));
HeapTuple tuple;
Datum result;
bool nulls[2]={false,false};
char * n = new char[2];
n[0] = '1';
n[1] = '\0';
char * m = new char[2];
m[0] = '2';
n[1] = '\0';
val[0] = CStringGetTextDatum(m);
val[1] = CStringGetTextDatum(n);
/* build a tuple */
tuple = heap_form_tuple(tupdesc, val, nulls);
/* make the tuple into a datum */
result = TupleGetDatum(funcctx->slot, tuple);
/* clean up (this is not really necessary) */
SRF_RETURN_NEXT(funcctx, result);
}
else
SRF_RETURN_DONE(funcctx);
}
代码与此处几乎相同:http://www.postgresql.org/docs/8.4/static/xfunc-c.html
如果该过程只返回一行,则一切正常,并且根据需要有一行的表。但如果一行改变如此
/* total number of tuples to be returned */
funcctx->max_calls = 2;
查询的执行因此消息而崩溃:
程序收到信号EXC_BAD_ACCESS,无法访问内存。 原因:KERN_INVALID_ADDRESS位于地址:0x000000000000041a heap_form_tuple()
中的0x0000000100002d8b
单步执行代码显示没有任何内容,直到崩溃是无效指针,所以我有点无能为力。还有其他我监督过的事吗?
编辑: 该函数在psql中被调用:
select (selectServeralRows()).*
编辑: SQL函数的定义:
CREATE OR REPLACE FUNCTION selectServeralRows()
RETURNS TABLE(k character varying(20), j character varying(20)) AS
'/opt/local/lib/postgresql84/Debug/libSeveralRows', 'selectServeralRows'
LANGUAGE c STABLE STRICT;
答案 0 :(得分:2)
您似乎省略了
tuple = BuildTupleFromCStrings(funcctx->attinmeta, val);
在TupleGetDatum(...)
电话前拨打电话。除第一次调用外,元组变量仍然未初始化。
此外,Datum* val = (Datum*)palloc(2 * sizeof(Datum));
应该是
char **val;
val = palloc (2 * sizeof *val);
n和m数组也可以;
char n[2] ="1", m[2] = "2";
val[0] = n;
val[1] = m;
您可以在致电之后将内存释放到heap_form_tuple(tupdesc, val, nulls);
pfree(val);
恕我直言'val'也可以是一个自动(“堆叠”)变量,就像n []和m []一样。