2

I am trying to wrap a C++ library for using in a C# WPF project. As part of that I need to pass and return large arrays from C# to C++ and return a large array back. Passing the array seems to be achieved like this:

namespace CppWrapper {

    public ref class CppWrapperClass
    {
    public:
        void DoStuff(int* pInt, int arraySize);
    private:        
        computingClass* pCC;
    };
}

And then called like this:

         int noElements = 1000;
         int[] myArray = new int[noElements];

         for (int i = 0; i < noElements; i++)
            myArray[i] = i * 10;

         unsafe
         {
            fixed (int* pmyArray = &myArray[0])
            {

               CppWrapper.CppWrapperClass controlCpp = new CppWrapper.CppWrapperClass();
               controlCpp.DoStuff(pmyArray, noElements);
            }

         }

How do I return an array?

Note: I would appreciate any feedback on the best way of achieving this. I am surprised it is not easier to this from C# to C++. I found it much easier wrapping the library with JNI.

Robben_Ford_Fan_boy
  • 8,494
  • 11
  • 64
  • 85
  • In general, there are several ways of interfacing C# to C++. With C++/CLI, you can use IJW 'It Just Works' to avoid a lot of boilerplate. Also beware of std library issues, so you do not malloc/new with one version of stdlib and then free/delete with another. – Erik Alapää Jun 16 '16 at 11:05
  • What kind of library is your C++ code? The question confuses me a little. The first code block looks like a C++ class declaration but the second appears to be the c#. However you wouldn't be able to directly call it like that. Is the C++ code managed C++ or C++/CLI? – Jarrett Robertson Jun 16 '16 at 11:13
  • Change it to `void DoStuff(array^ arr);` Get rid of all that unnecessary C# code, just add a reference to the DLL and call DoStuff() directly. Simple enough? – Hans Passant Jun 16 '16 at 11:55
  • If you can't use CLI because of external dependency, you can still pass arrays around like this: http://stackoverflow.com/questions/17634480/return-c-array-to-c-sharp – Luke Dupin Oct 25 '16 at 18:49

0 Answers0