The Vivandiere
The Vivandiere

Reputation: 3201

Exporting an image struct from native code to managed

I have a native codebase that creates an image every 50 ms. I want to use WPF to render this image into a WPF GUI view.

The image is an hbitmap constructed from a data structure of type boost::numeric::ublas::matrix. i.e. I start with a matrix of float values, then I create a HBITMAP, and then draw this HBITMAP using the device context of MFC. But now, I want to replace my MFC GUI with a WPF GUI, because it looks nicer. I plan to use C++/CLI to achieve the interop.

My question is as follows : How should I setup the transfer of my image across the interop boundary?

Should I transfer it over while it is still a structure of floats, or shall I transfer after I created the bitmap? I have heard marshaling is a big drain on efficiency, and so must be handled very carefully. Is there a type that is common to managed and native world, that can be used for this?

I am a complete newbie to interoping, any other related resources you share will be greatly appreciated.

Or, is there a way to completely avoid the transfer? - by drawing from native code into a WPF GUI view

My application is very performance sensitive, any alternative you suggest that achieves good performance will be greatly appreciated.

Upvotes: 1

Views: 182

Answers (1)

Roger Rowland
Roger Rowland

Reputation: 26279

I've been through the same options and found that - at least for .NET 4.5 - the InteropBitmap is the best way to go, as long as your image stays the same size (e.g. for something like video streaming).

In brief, you create a memory mapped file (either in using C++/CLI or C# with p/invoke), and use that as the source of pixel data. The InteropBitmap is created over that same memory mapped file, and you can use it as an ImageSource in WPF.

In my application, a background thread updates the MMF and invalidates the InteropBitmap and the WPF front end just binds to the image source as normal.

Upvotes: 1

Related Questions