call cgal in csharp

To call CGAL in C# you can use Interop and Platform Invoke (P/Invoke) techniques. The following steps outline the general process:

  1. Define the CGAL functions in a C++ header file that can be linked against your C# application.
extern "C" __declspec(dllexport) void computeConvexHull(double* points, int numPoints, double* hullVertices, int* hullSize);
125 chars
2 lines
  1. Define the CGAL functions in a C++ source file.
#include <CGAL/convex_hull_2.h>
#include <vector>

typedef CGAL::Exact_predicates_exact_constructions_kernel K;
typedef K::Point_2 Point;
typedef K::Vector_2 Vector;
typedef K::Segment_2 Segment;
typedef K::Ray_2 Ray;
typedef K::Line_2 Line;

extern "C" __declspec(dllexport) void computeConvexHull(double* points, int numPoints, double* hullVertices, int* hullSize)
{
    std::vector<Point> pts;
    for (size_t i = 0; i < numPoints; i++)
    {
        Point pt(points[i * 2], points[i * 2 + 1]);
        pts.push_back(pt);
    }

    std::vector<Point> hull;
    CGAL::convex_hull_2(pts.begin(), pts.end(), std::back_inserter(hull));

    int i = 0;
    for (auto pt : hull)
    {
        hullVertices[i * 2] = pt.x();
        hullVertices[i * 2 + 1] = pt.y();
        i++;
    }

    *hullSize = static_cast<int>(hull.size());
}
832 chars
33 lines
  1. Build the CGAL library (or use an existing one) with a compatible architecture and C++ compiler flags.
mkdir build && cd build
cmake ..
make
38 chars
4 lines
  1. Build a dynamic link library (DLL) from the source file containing the CGAL functions.
cl.exe /LD compute_convex_hull.cpp /I "path/to/cgal/include/directory/" /link "path/to/cgal/library/cgal.lib"
110 chars
2 lines
  1. Create a C# class containing the P/Invoke declarations for the CGAL functions.
main.cs
using System;
using System.Runtime.InteropServices;

public static class CGALInterop
{
    [DllImport("path/to/compute_convex_hull.dll")]
    public static extern void computeConvexHull(double[] points, int numPoints, double[] hullVertices, out int hullSize);
}
262 chars
9 lines
  1. Call the CGAL functions using the P/Invoke declarations.
main.cs
double[] pts = { 0, 0, 1, 1, 2, 2 };
double[] hull = new double[6];
int hullSize;

CGALInterop.computeConvexHull(pts, 3, hull, out hullSize);

for (int i = 0; i < hullSize; i++)
{
    Console.WriteLine("({0}, {1})", hull[i * 2], hull[i * 2 + 1]);
}
249 chars
11 lines

gistlibby LogSnag