views:

388

answers:

4

Hi All,

After asking this question and apparently stumping people, how's about this for a thought-- could I give a buffer from a C# application to a C++ dll, and then have a timing event in C# just copy the contents of the buffer out? That way, I avoid any delays caused by callback calling that apparently happen. Would that work, or does marshalling prevent that kind of buffer access? Or would I have to go to unsafe mode, and if I do or don't, what would be the magic words to make it work?

To recap from that other question:

  • I have a driver written in C++ and an app written in C#.
  • I need to get data from the driver in a preview-style manner.
  • C++ applications interact with the C++ dll just fine; the C# app has a large delay for copying the data over.
  • The delay does not appear to be caused by release/debug differences on the C# side
  • I need to get around the delay. Could this proposed buffer scheme work? Could a C# app consume from a buffer written to by a C++ dll, or do I need to do something else?
A: 

Yes, you can pass a buffer (eg. byte[]) from C# to C++. I am stumped by your original problem. I use callbacks from my own C++ code to C# and I have never noticed a performance problem--although I try not to do callbacks on every iteration of a loop, as I do expect some marshaling overhead.

Qwertie
+1  A: 

For the main reason PInvoke is slow and what to use to solve this see SuppressUnmanagedCodeSecurityAttribute.

VirtualBlackFox
+2  A: 

If you wish to

  1. Consume data from unmanaged code in managed code
    Then you have an issue unless you consume it as a byte pointer (unsafe code) or you take a copy (which marshaling will do fo you). It is likely the latter which is slowing you down (but don't guess benchmark).

  2. Consume data from managed code in unmanaged code
    Then this is pretty simple you just have to make sure you pin the associated buffer whilst it is being used by the unmanaged code.

It sounds like you wish to do 1. Have you benchmarked the delay? If it is the copying (how big is the buffer out of interest) then can you change your c# code to interact with the buffer as a byte pointer (and length)?
If you have access to C++/CLI you can often work around this more cleanly since it is easier to have parts of the code unmanaged (working with the raw buffer) and the parts that are managed just work with sub sections of it (copying only what is absolutely required)

ShuggyCoUk
A: 

As I said in the other thread, it seems the delay was entirely on the C++ side, so no amount of finagling on my end was going to fix the problem.

mmr