C# app to C++ dll back to the C# app via callbacks

2019-02-25 21:42发布

I'm writing a C# application that calls a C++ dll. This dll is a device driver for an imaging system; when the image is being acquired, a preview of the image is available from the library on a line-by-line basis. The C++ dll takes a callback to fill in the preview, and that callback consists basically of the size of the final image, the currently scanned line, and the line of data itself.

Problem is, there's a pretty serious delay from the time when scanning stops and the C# callback stops getting information. The flow of the program goes something like:

  1. Assign callback to C++ dll from within C#
  2. User starts to get data
  3. Device starts up
  4. dll starts to call the callback after a few seconds (normal)
  5. Device finishes image formation
  6. dll is still calling the callback for double the time of image formation.

This same dll worked with a C++ application just fine; there does not appear to be that last step delay. In C#, however, if I have the callback immediately return, the delay still exists; no matter what I do inside the callback, it's there.

Is this delay an inherent limitation of calling managed code from unmanaged code, or is there something either side could do to make this go faster? I am in contact with the C++ library writer, so it's possible to implement a fix from the C++ side.

Edit: Could doing something simple like a named pipe work? Could an application read from its own pipe?

3条回答
该账号已被封号
2楼-- · 2019-02-25 22:27

Are you doing any funky data marshalling across the interop layer? If so then you may have a huge delay whilst it's basically marshalling all your image data by converting it. You can easily test this as the large the image data, the longer it will take

A few possible alternatives that spring to mind are
1.Use a memory mapped file though you'd need to implement a simple semaphore or signalling system to say 'I have data ready' and 'I have consumed the data
2. Compile the C++ dll in mixed mode ( any C++ code can be compiled into .NET with the /clr flag ) then use C#/CLI
3. Use Remoting and IPC Channels - maybe a bit of an overkill but worth a look

Hope that helps

查看更多
smile是对你的礼貌
3楼-- · 2019-02-25 22:34

Turns out the delay is in the C++ side, by a developer who swore up and down it wasn't.

查看更多
干净又极端
4楼-- · 2019-02-25 22:37

It may be possible that the Managed Debug Assistant that checks native callbacks for garbage collected targets may be the culprit (is it in debug mode under the debugger?)

See the PSA: Pinvokes may be 100x slower under the debugger blog entry by Mike Stall.

查看更多
登录 后发表回答