开发者

How do I use this native array in my .NET class?

开发者 https://www.devze.com 2023-01-30 17:19 出处:网络
I\'m working on updating the GUI of a native (MFC) application using .NET and WPF. The application collects data in real-time and the GUI is supposed to visualize that data (in real-time). The overall

I'm working on updating the GUI of a native (MFC) application using .NET and WPF. The application collects data in real-time and the GUI is supposed to visualize that data (in real-time). The overall plan is to use C++/CLI as an interoperability layer between the native application and the managed GUI part.

I've got a native class with byte arrays containing a "header" giving the length of the array and the type of the elements in it. I'm trying to write an interoperability layer in C++/CLI between this native class and a managed .NET class.

I want to use the unmanaged byte array in the managed part of the application. I'm somewhat overwhelmed by information on various blogs and documentation centers. This is the outline of what I've got so far, it kind of works but crashes sometimes*. I'm not sure if this is the most appropriate solution, or even how to properly implement it. I would like to know if there is a more suitable approach?

// Fetch numbers from the native class into unmanaged memory.
IntPtr ipNumbers = InteropServices::Marshal::AllocHGlobal(sizeof(int) * arrayLength))
nativeClass->fetchNumbers((int *) ipNumbers.ToPointer(), arrayLength);

// Copy data from unmanaged memory into a managed array.
cli::array<int, 1> ^numbers = gcnew cli::array<int, 1>(arrayLength);
InteropServices::Mar开发者_JS百科shal::Copy(ipNumbers, numbers, 0, arrayLength);
InteropServices::Marshal::FreeHGlobal(ipNumbers);

*) Crash message: "Windows has triggered a breakpoint in MyProgram.exe. This may be due to a corruption of the heap, which indicates a bug in MyProgram.exe or any of the DLLs it has loaded. [...]". From what I can tell it's FreeHGlobal that causes the crash.


Taking Mattias' suggestion into consideration I changed the code, and it's now working.

cli::array<int, 1> ^numbers = gcnew cli::array<int, 1>(arrayLength);
pin_ptr<int> pp = &numbers[0];
nativeClass->fetchNumbers(pp, arrayLength);
0

精彩评论

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

关注公众号