Marshalling std::vector


  • Hello,

    I have a C++ DLL that exposes the following function prototype:
    void foo(std::vector<SomeClass>& vec);

    I want to call this function from a .NET application written in C#.
    I couldn't quite figure how to write the function prototype in C#. One thing that I do know though: A vector can be converted to a C-style array by accessing &vec[0];. So it is theortically possible to initialize a managed array of say SomeClass[] or array<SomeClass^>^, I just don't know how and if that's recommended.

    For the time being I wrote a CLI proxy that iterates the vector and inserts it's items to a List<T>.
    A few problems with this solution:
    1. I go over the data of the container twice.
    2. I think I duplicate the data in it. Meaning it sits both in the vector and in the List at the same time.

    Eventually I want to solve the 2 problems I mentioned above and suffer as little as possible from the passage from managed to unmanaged code and vice versa.

    Saturday, December 22, 2007 8:21 PM


All replies

  • You can't marshal classes, only structures.


    If you want to marshal std::vector back and forth from C++, I'd suggest writing a wrapper for it in C++/CLI that can be accessed in C#. provides a good overview of doing this.


    Monday, December 24, 2007 2:38 AM
  • Can some one please provide me a sample code showing how to do this. I would like to pass data back and forth between native c++ (not COM) and c# through std::vector.

    Sunday, October 18, 2009 10:11 PM