开发者

Native C++ array to C# array via C++/CLI

开发者 https://www.devze.com 2023-02-02 21:24 出处:网络
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 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));
...
wr开发者_Go百科apper->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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消