1

I have a native C++ application that needs to call a C# library. After investigating the different options, I opted to add a C++/CLI library as a wrapper to handle the direct interface between the two. I have a VERY large array that I am passing from the C++ to the C# (so large that making a copy via Marshal::Copy is out of the question). I have been unable to solve the syntax.

C# function declaration:

void Computation::passInVolume(int size, short volume[])

C++/CLI function:

void Wrapper::passInVolume(int size, short volume[])
{
    //this call succeeds, but does not contain my data
    array<short>^ locArray = gcnew array<short>(size);

    // This line produces: error C2440: 'type cast' : cannot convert from 
    // 'short []' to 'cli::array<Type> ^'   
    array<short>^ locArray2 = (array<short>^)volume;

    // call requires array<short>^ as input type
    Computation::passInVolume(size, locArray); 
}

C++ code:

volImage = (short*)malloc(size*sizeof(short));
...
wrapper->passInVolume(size, volImage);

Is there a way to cast this that I am just missing? I have successfully done this the other way, calling a C++ from C#, in the past without any issues (or even any casting).

1
  • It's a bit surprising that the "heavy duty" code is on the C# side. Commented Oct 15, 2019 at 14:12

1 Answer 1

1

making a copy via Marshal::Copy is out of the question

Too bad. .NET arrays are always on the managed heap, you cannot convince .NET to do otherwise.

You still have a few options which don't involve copying:

  • Rewrite the C# code to use pointers (and of course add extra parameters where needed, to carry the length). C# can use a pointer that was allocated natively, and perform pointer arithmetic to find the remaining elements.

  • Rewrite the C++ library to use an externally-provided buffer. Since C++ already uses pointers, you can pin a C# array in place and pass a pointer to its contents to the native library.

Sign up to request clarification or add additional context in comments.

1 Comment

I ended up refactoring to C# use pointers. Effort wasn't as bad as I initially thought.

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.