Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access native memory transparently from .NET assembly

I am in the process of evaluating the possibilities to implement a plugin infrastructure for a native application that allows extensions to be written in managed code. The plugins will operate on large(-ish) floating point buffers allocated on the native heap which are fairly expensive in terms of memory footprint to copy. As a consequence a plugin should be able to operate on the native memory directly.

As far as I understand it is possible to access native memory from managed code by using Unsafe Code and Pointers (to my understanding this is the only provision in the .NET framework to do so). To ease development of plugins I would rather not expose this artifact and provide a proxy mechanism instead so that buffers can be accessed like managed collections.

There are no restrictions as to the implementation (a C++/CLI interop layer is fine, for example) or a specific .NET runtime version. The buffers can be assumed to be of fixed size as well; the plugin will modify the contents only.

Is it possible to implement an infrastructure that meets the requirements layed out above and if so, what options exist?

like image 465
IInspectable Avatar asked Aug 21 '13 16:08

IInspectable


1 Answers

Is it possible to implement an infrastructure that meets the requirements layed out above and if so, what options exist?

You won't be able to treat the native data as a managed array directly, but you can expose a layer via C++/CLI that allows direct, indexable access to that memory.

For example, suppose you have a buffer comprised of a few million double precision floating point values. You can easily make a C++/CLI ref class that exposes a window onto that buffer via an indexer, or even better, as an IList<T>.

This would potentially allow it to be used from C# as if it were a normal IList<T>, without copying the data, as the wrapper class only needs the buffer memory locations stored.

like image 64
Reed Copsey Avatar answered Oct 05 '22 23:10

Reed Copsey