Howto call an unmanaged C++ function with a std::vector as parameter from C#?

前端 未结 4 1010
孤街浪徒
孤街浪徒 2020-12-12 01:04

I have a C# front end and a C++ backend for performance reasons. Now I would like to call a C++ function like for example:

void findNeighbors(Point p, std::v         


        
4条回答
  •  忘掉有多难
    2020-12-12 01:29

    The impedance mismatch is severe. You have to write a wrapper in the C++/CLI language so that you can construct a vector. An additional problem is Point, your C++ declaration for it is not compatible with the managed version of it. Your code ought to resemble this, add it to a class library project from the CLR node.

    #include 
    
    using namespace System;
    using namespace System::Collections::Generic;
    
    struct Point { int x; int y; };
    void findNeighbors(Point p, std::vector &neighbors, double maxDist);
    
    namespace Mumble {
    
        public ref class Wrapper
        {
        public:
            List^ FindNeigbors(System::Drawing::Point p, double maxDist) {
                std::vector neighbors;
                Point point; point.x = p.X; point.y = p.Y;
                findNeighbors(point, neighbors, maxDist);
                List^ retval = gcnew List();
                for (std::vector::iterator it = neighbors.begin(); it != neighbors.end(); ++it) {
                    retval->Add(System::Drawing::Point(it->x, it->y));
                }
                return retval;
            }
        };
    }
    

    Do note the cost of copying the collection, this can quickly erase the perf advantage you might get out of writing the algorithm in native C++.

提交回复
热议问题