Reputation: 14919
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:
Upvotes: 3
Views: 844
Reputation: 14919
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.
Upvotes: 0
Reputation: 36448
If you wish to
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).
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)
Upvotes: 2
Reputation: 17837
For the main reason PInvoke is slow and what to use to solve this see SuppressUnmanagedCodeSecurityAttribute.
Upvotes: 1
Reputation: 17196
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.
Upvotes: 0