Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/C# callback continued

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?
like image 337
mmr Avatar asked Feb 26 '26 20:02

mmr


1 Answers

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)

like image 103
ShuggyCoUk Avatar answered Mar 01 '26 10:03

ShuggyCoUk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!