Search code examples
vectorc++-cliwrapperunmanagedmixed-mode

How to pass a vector as parameter to a c++ library from a CLI/C++ Wrapper?


I have found similar questions but none that worked for my situation, so I am asking my own.

I want to use a library function that takes a pointer to a std::vector, and fills it with data.

I already have a C++/CLI Wrapper set up. I am currently trying to instantiate the vector in the wrapper,

private:
   std::vector<int>* outputVector

and in the constructor, I instantiate it :

outputVector = new std::vector<int>();

Now, in the wrapper method that calls the c++ library function :

m_pUnmanagedTPRTreeClass->GetInRegion(..., &outputVector)

I omitted the other parameters because they dont matter for this case. I can already use other functions of the library and they work without a problem. I just can't manage to pass a pointer to a std::vector.

With the code like this, I get the error message :

error C2664: 'TPSimpleRTree<CT,T>::GetInRegion' : cannot convert parameter 3 from 'cli::interior_ptr<Type>' to 'std::vector<_Ty> &' 

I have tried removing the "&", as I am not great at C++ and am unsure how to correctly use pointers. Then, the error becomes :

error C2664: 'TPSimpleRTree<CT,T>::GetInRegion' : cannot convert parameter 3 from 'std::vector<_Ty> *' to 'std::vector<_Ty> &'  

EDIT: I have tried replacing "&" by "*", it does not work, I get the error :

cannot convert from 'std::vector<_Ty>' to 'std::vector<_Ty> &'

The signature of the c++ function for the vector is so :

GetInRegion(..., std::vector<T*>& a_objects)

Solution

  • Given the signature:

    GetInRegion(..., std::vector<T*>& a_objects)
    

    You would call this (in C++ or C++/CLI) like:

    std::vector<int*> v;
    m_pUnmanagedTPRTreeClass->GetInRegion(..., v);
    

    Then you can manipulate the data as needed or marshall the data into a .Net container.