Converting Between OGRGeometry* and OGRGeometryH in GDAL/OGR

Answered using GPT-4o by GPT4oMini.app

Question:

convert OGRGeometry* to OGRGeometryH

Answer:

In the GDAL (Geospatial Data Abstraction Library) library, OGRGeometry* is a C++ pointer to an OGRGeometry object, while OGRGeometryH is a handle to an OGRGeometry object used in the C API. The conversion between these two types is straightforward because OGRGeometryH is essentially a typedef for void*, which can be used to hold a pointer to any type.

Here’s how you can convert between OGRGeometry* and OGRGeometryH:

From OGRGeometry* to OGRGeometryH

To convert an OGRGeometry* to an OGRGeometryH, you can simply cast the pointer:

OGRGeometry* poGeometry = ...; // Assume this is already created and initialized
OGRGeometryH hGeometry = reinterpret_cast<OGRGeometryH>(poGeometry);

From OGRGeometryH to OGRGeometry*

To convert an OGRGeometryH back to an OGRGeometry*, you can also use a cast:

OGRGeometryH hGeometry = ...; // Assume this is already created and initialized
OGRGeometry* poGeometry = reinterpret_cast<OGRGeometry*>(hGeometry);

Example Usage

Here is a complete example demonstrating both conversions:

#include "ogrsf_frmts.h"

int main() {
    // Initialize GDAL/OGR
    OGRRegisterAll();

    // Create a point geometry
    OGRPoint* poPoint = new OGRPoint(1.0, 2.0);

    // Convert OGRGeometry* to OGRGeometryH
    OGRGeometryH hGeometry = reinterpret_cast<OGRGeometryH>(poPoint);

    // Perform some operations using the C API
    // For example, get the geometry type
    OGRwkbGeometryType eType = OGR_G_GetGeometryType(hGeometry);
    printf("Geometry type: %d\n", eType);

    // Convert OGRGeometryH back to OGRGeometry*
    OGRGeometry* poGeometry = reinterpret_cast<OGRGeometry*>(hGeometry);

    // Perform some operations using the C++ API
    // For example, export to WKT
    char* pszWKT = nullptr;
    poGeometry->exportToWkt(&pszWKT);
    printf("WKT: %s\n", pszWKT);
    CPLFree(pszWKT);

    // Clean up
    delete poPoint;

    // Cleanup GDAL/OGR
    OGRCleanupAll();

    return 0;
}

In this example:

  • We create an OGRPoint object using the C++ API.
  • We convert the OGRPoint* to an OGRGeometryH handle.
  • We use the C API to get the geometry type.
  • We convert the OGRGeometryH handle back to an OGRGeometry*.
  • We use the C++ API to export the geometry to WKT (Well-Known Text).
  • Finally, we clean up the allocated resources.

This demonstrates how you can seamlessly switch between the C++ and C APIs in GDAL/OGR by casting between OGRGeometry* and OGRGeometryH.