[postgis-devel] PgSQL Memory Stuff

Paul Ramsey pramsey at cleverelephant.ca
Tue Dec 7 16:27:36 PST 2010


Nik,
Here's an annotated version of one of your functions, none of this
stuff is critical, since pgsql just cleans right up behind you, but in
case you want to do it "right"...


PG_FUNCTION_INFO_V1(LWGEOM_shortestline2d);
Datum LWGEOM_shortestline2d(PG_FUNCTION_ARGS)
{
	PG_LWGEOM *result;
	/* Detoast the actual PgSQL varlena structures, in our case PG_LWGEOM
(soon to be GSERIALIZED) */
	PG_LWGEOM *geom1 = (PG_LWGEOM*)PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
	PG_LWGEOM *geom2 = (PG_LWGEOM*)PG_DETOAST_DATUM(PG_GETARG_DATUM(1));
	/* Build LWGEOM from the varlena (soon to be with lwgeom_from_gserialized) */
	LWGEOM *lwgeom1 = pglwgeom_deserialize(geom1);
	LWGEOM *lwgeom2 = pglwgeom_deserialize(geom2);
	LWGEOM *theline;


	if (lwgeom1->srid != lwgeom2->srid)
	{
		elog(ERROR,"Operation on two GEOMETRIES with different SRIDs\n");
		PG_RETURN_NULL();
	}

	theline = lw_dist2d_distanceline(lwgeom1, lwgeom2, lwgeom1->srid, DIST_MIN);
	if (lwgeom_is_empty(theline))
		PG_RETURN_NULL();

	/* Serialize the result back down from LWGEOM, but don't return right away */
	result = pglwgeom_serialize(theline);
	/* First free the LWGEOMs you used */
	lwgeom_free(lwgeom1);
	lwgeom_free(lwgeom2);

	/* Then call free_if_copy on the *varlena* structures you originally
get as arguments */
	PG_FREE_IF_COPY(geom1, 0);
	PG_FREE_IF_COPY(geom2, 1);

	/* And now return */
	PG_RETURN_POINTER(result);
}



More information about the postgis-devel mailing list