开发者

How to call an unmanaged C++ function with a std::vector<>::iterator as parameter from C#?

开发者 https://www.devze.com 2023-03-21 01:10 出处:网络
In unmanaged C++ I have a function which I\'m trying to call from C#.This C++ function is as follows:

In unmanaged C++ I have a function which I'm trying to call from C#. This C++ function is as follows:

typedef std::vector<Point> Points;
typedef std::back_insert_iterator<Points> OutputIterator;

namespace MYNAMESPACE{
    DLLEXPORT OutputIterator convexHull(Points::iterator first, Points::iterator last,  OutputIterator result);
}

When called from C++, the function is used as follows:

  Points points, result;

  points.push_back(Point(0,0));
  points.push_back(Point(10,0));
  points.push_back(Point(10,10));
  points.push_back(Point(6,5));
  points.push_back(Point(4,1));

  OutputIterator resultIterator = std::back_inserter(result);

  MYNAMESPACE::convexHull( points.begin(), points.end(), resultIterator);
  std::cout << result.size() << " points on the convex hull" << std开发者_如何学Go::endl;

I've started writing the C# code, but I've no idea what types I should be passing:

[DllImport("unmanagedCode.dll", EntryPoint = "convexHull", CallingConvention = CallingConvention.StdCall)]
        public static extern ???<Point> convex_hull_2(???<Point> start, ???<Point> last, ???<Point> result);

The Point structure in C# is just:

struct Point{
    double x;
    double y;
}

Is it a case of passing an array or List of Point?

I have the source to the C++ and can make changes to the function parameters; would there be a different type of parameters which would be easier to call from C#?


Use a C++/CLI wrapper class (since you have the C++ source, you can compile it together with the existing code into a single DLL).

P/invoke isn't designed for interacting with C++ classes, and any attempt to do so is extremely fragile. C++ templates may it even worse. Don't try it. Even dllexporting that function to other C++ code is a terrible idea, STL classes such as vector and vector::iterator shouldn't be passed across DLL boundaries.

Use /clr and let the Visual C++ compiler take care of the details.


Passing C++ types through P/Invoke is not going to work. You don't know their layout and nothing guarantees they won't change. P/Invoke is really only meant for inter-operating with C.

One option is to use C++/CLI instead of C++. This won't be portable (only supported with VC++/Windows), but it might be the easiest solution depending on how large your C++ code is already.

If you want to remain portable and use straight P/Invoke from C#, your best bet is to slightly refactor the C++ convexHull and provide a new function callable from C (and thus P/Invoke).

// C-safe struct.
struct Results
{
    Point *points;
    std::size_t num_points;
};

// Store the real results in a vector, but derive from the C-safe struct.
struct ResultsImpl : Results
{
    Points storage;
};

// convexHull has been refactored to take pointers
// instead of vector iterators.
OutputIterator convexHull(Point const *first, Point const *last,
    OutputIterator result);

// The exported function is callable from C.
// It returns a C-safe Results, not ResultsImpl.
extern "C" DLLEXPORT Results* convexHullC(Point const *points,
                                          std::size_t num_points)
{
    try
    {
        std::unique_ptr<ResultsImpl> r(new ResultImpl);

        // fill in r->storage.
        convexHull(points, points + num_points,
            std::back_inserter(r->storage));

        // fill in C-safe members.
        r->points = &r->storage[0];
        r->numPoints = &r->storage.size();

        return r.release();
    }
    catch(...)
    {
        // trap all exceptions!
        return 0;
    }
}

// needs to be called from C# to clean up the results.
extern "C" DLLEXPORT void freeConvexHullC(Results *r)
{
    try
    {
        delete (ResultsImpl*)r;
    }
    catch(...)
    {
        // trap all exceptions!
    }
}

And then from C#:

[StructLayout(LayoutKind.Sequential)]
struct Point
{
    double x;
    double y;
}

[StructLayout(LayoutKind.Sequential)]
struct Results
{
    IntPtr points;
    IntPtr num_points;
}

[DllImport("unmanagedCode")]
IntPtr convexHullC(Point[] points, IntPtr pointCount);

[DllImport("unmanagedCode")]
void freeConvexHullC(IntPtr results);

Point[] ConvexHull(Point[] points)
{
    IntPtr pr = convexHull(points, new IntPtr(points.Length));

    if(pr == IntPtr.Zero)
    {
        throw new Exception("native error!");
    }

    try
    {
        Results r = Marshal.PtrToStructure(pr, typeof(Results));

        points = new Point[checked((int)(long)r.num_points)];

        for(int i = 0; i < points.Length; ++i)
        {
            points[i] = Marshal.PtrToStructure(
                r.points + Marshal.Sizeof(typeof(Point)) * i,
                typeof(Point));
        }

        return points;
    }
    finally
    {
        freeConvexHull(pr);
    }
}

Code not tested!

0

精彩评论

暂无评论...
验证码 换一张
取 消