How to convert System::array to std::vector?

前端 未结 2 1435
广开言路
广开言路 2020-12-17 00:09

Is there any easy way to convert a CLI/.NET System::array to a C++ std::vector, besides doing it element-wise?

I\'m writing a wrapper metho

2条回答
  •  生来不讨喜
    2020-12-17 00:59

    Another approach, letting the .NET BCL do the work instead of the C++ standard library:

    #include 
    
    void SetLowerBoundsWrapper(array^ lb)
    {
        using System::IntPtr;
        using System::Runtime::InteropServices::Marshal;
    
        std::vector lower(lb->Length);
        Marshal::Copy(lb, 0, IntPtr(&lower[0]), lb->Length);
        _opt->set_lower_bounds(lower);
    }
    

    The following both compile for me with VC++ 2010 SP1, and are exactly equivalent:

    #include 
    #include 
    
    void SetLowerBoundsWrapper(array^ lb)
    {
        std::vector lower(lb->Length);
        {
            pin_ptr pin(&lb[0]);
            double *first(pin), *last(pin + lb->Length);
            std::copy(first, last, lower.begin());
        }
        _opt->set_lower_bounds(lower);
    }
    
    void SetLowerBoundsWrapper2(array^ lb)
    {
        std::vector lower(lb->Length);
        {
            pin_ptr pin(&lb[0]);
            std::copy(
                static_cast(pin),
                static_cast(pin + lb->Length),
                lower.begin()
            );
        }
        _opt->set_lower_bounds(lower);
    }
    

    The artificial scope is to allow the pin_ptr to unpin the memory as early as possible, so as not to hinder the GC.

提交回复
热议问题