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.

4
  • 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. Commented Jun 16, 2016 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? Commented Jun 16, 2016 at 11:13
  • Change it to void DoStuff(array<int>^ arr); Get rid of all that unnecessary C# code, just add a reference to the DLL and call DoStuff() directly. Simple enough? Commented Jun 16, 2016 at 11:55
  • If you can't use CLI because of external dependency, you can still pass arrays around like this: stackoverflow.com/questions/17634480/return-c-array-to-c-sharp Commented Oct 25, 2016 at 18:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.