Calling an unmanaged DLL from C# (for performance)
Posted on 2007-07-21
I have a situation in which I need to get a lot of system level data from the Win32 API. There is a .NET API made specifically for getting this data and it produces correct results. However, it is pretty slow. I needed to speed up the performance, so I wrote a lot of in unmanaged code in VC++. The bottom line is that when comparing the retrieval of data, and I have meticulously benchmarked it, the unmanaged code is 85% faster. In fact, the amount of data that will bet gather can range from 640KB to maybe a 100MB, and my 85% speedup is comparing the unmanaged code gathering the data AND writing it out, while the C# version merely reads it.
I've compared my C++ code to the Reflector output of the .NET API that is equivalent, and I think I know why the .NET implementation is so slow, but in any event I need to use this unmanaged code. The thing is, I'll be doing this retrieval from a .NET Windows Service.
What is the best way to call my unmanaged code from C# to get the best performance? Basically, I *ultimately* want to populate a .NET DataTable with this data. There can be anywhere from 400 - 100,000 rows of data and, again, 640KB-100MB of data. I guess the strategy is to reduce the amount of marshaling? (The C++ data is currently stored in a class but can be changed to a struct)
Anyway, what is the best way to do this to preserve performance? Doing a managed C++ DLL and then calling the Win32 code could be an option, though I've never used managed extensions for C++. But would that do much in the way of performance over calling the unamanged stuff from C#, since either way there its crossing the border between managed and unmanaged?
(Just to clarify, I know about P/Invoke. Its not a question of whether its possible to do this but what is the best method from a performance perspective.)