How can I marshall a vector from a C++ dll to a C# application?

前端 未结 3 994
名媛妹妹
名媛妹妹 2020-12-10 06:26

I have a C++ function that produces a list of rectangles that are interesting. I want to be able to get that list out of the C++ library and back into the C# application th

3条回答
  •  星月不相逢
    2020-12-10 07:04

    The STL is a C++ specific library, so you cant directly get it across as one object to C#.

    The one thing that is guaranteed about std::vector is that &v[0] points to the first element and all the elements lie linearly in memory (in other words, its just like a C array in terms of memory layout)

    So marshal as array of int... which shouldn't be hard - There are lot of examples on the web.

    Added

    Assuming you only pass the data from C++ to C# :

    C# cannot handle a C++ vector object, so do not try passing it by reference : Instead your C++ code must return a pointer to an array of ints...

    If you are not going to be using this function from multiple threads, you can use static storage :

    int *getRects(bool bClear)
    {
        static vector v; // This variable persists across invocations
        if(bClear)
        {
            v.swap(vector());
        }
        else
        {
            v.clear();
            // Fill v with data as you wish
        }
    
        return v.size() ? &v[0] : NULL;
    }
    

    call getRects(true) if the returned data is significant in size, so you release the memory in v.

    For simplicity, instead of passing out the size of the vector data too, just put a sentinel value at the end (like say -1) so the C# code can detect where the data ends.

提交回复
热议问题