views:

198

answers:

2

I have an native C++ library which makes use of a large static buffer (it acquires data from a device).

Let's say this buffer is defined like this:

unsigned char LargeBuffer[1000000];

Now I would like to expose parts of this buffer to managed C++, e.g. when 1000 bytes of new data are stored by the library at LargeBuffer[5000] I would like to perform a callback into managed C++ code, passing a pointer to LargeBuffer[5000] so that managed C++ can access the 1000 bytes of data there (directly if possibile, i.e. without copying data, to achieve maximum performance).

What is the best way to let managed C++ code access data in this native array?

+3  A: 

Managed C++ can access the unmanaged memory just fine. You can just pass in the pointer and use it in managed c++.

Now, if you want to then pass that data into other .NET languages, you'll need to copy that data over to managed memory structures or use unsafe code in C#

Joe Doyle
Actually I'll have to pass back the data from managed C++ to C# so I guess I'll have to use unsafe code.
Enrico Detoma
CLI C++ and C# mix perfectly fine, there is no need for the unsafe keyword.
@high6: There is if he wants to access the raw pointer from C#.
Joe Doyle
+1  A: 

As of .net 2.0 and the new IJW you should be able to access the buffer directly from CLI C++.

As long as you dont specify "#pragma unmanaged" then the code will be compiled as a form of managed which is what allows the direct access.

Ok from C++, but if I want to access the raw pointer from C# too, I'll have to use unsafe keyword. Thanks for pointing me to IJW: I know very little about the managed-unmanaged mechanisms, now I'm understanding a bit more.
Enrico Detoma