Mixing unmanaged C++ and C#

J

Jon Slaughter

How difficult is it for one to integrate unmanaged C++ into C#? I know for
functions one can use DLLimport but how does one go about doing it for
classes? Do I have to completely reimplement the classes in managed C++ as a
wrapper to the unmanaged C++ classes or is there an easier way?

Essentially what I have done is written a C++ kernel mode driver and I want
to use it from my C# program. Because it requires some setup outside the
kernel(because it has to pass buffers back and forth and extract the
information out of the buffers) I'd rather keep the that specific code
unmanaged because its probably slightly faster.

But I don't want to have a huge number of dll imports and write a C# wrapper
class over each of the imports because it seems a little excessive. (Not
only does the driver internally use a similar class but I'd essentially be
implementing the same class 3 times... one in the driver, which is actually
slightly different but pretty much with same interface, one in unmanaged C++
to interface with the driver, and some type of managed wrapper.)

Is there a better way? Can I just mix unmanaged and managed C++ in the same
project to do all the work and not have to end up with a C# wrapper?
Basically I think I can get away with just using unsafe code to work with
the buffers. I'm mainly worried about the performance hit associated with
doing this. From my initial tests C# is anywhere from 2-5 times slower at
calling kernel mode drivers than unmanaged C++(not sure if I can get any
speed up by indirectly referencing unamanged C++ though so I might take that
hit no matter what if I plan on using C#). Of course I don't want to end up
with having to change 3 classes every time I make a simple change either.

Any ideas?

Thanks,
Jon
 
P

Peter Duniho

Jon said:
How difficult is it for one to integrate unmanaged C++ into C#? I know for
functions one can use DLLimport but how does one go about doing it for
classes?

I don't know the specifics, but my impression was that you can DllImport
C++ classes, COM, etc. in similar ways to doing it for individual functions.
Do I have to completely reimplement the classes in managed C++ as a
wrapper to the unmanaged C++ classes or is there an easier way?

I personally don't find p/invoke (DllImport) all that easy, mainly
because MSDN doesn't seem to have any really good, easily-navigated and
thorough documentation on the topic. You know the docs are lacking when
the most common reference is a 3rd-party site. In this case,
http://www.pinvoke.net/ is the one that seems to come up a lot more often.

You might want to start there. I don't know how long they've had this,
but I just noticed they have a VS add-in that is supposed to make it
easy to add DllImport signatures to your project. It's mentioned on the
front page. Looks like it could be an incredible time-saver.
[...]
Is there a better way? Can I just mix unmanaged and managed C++ in the same
project to do all the work and not have to end up with a C# wrapper?

Of course. Just as you could call unmanaged code from managed C++ to
create your own wrapper, you could just implement everything in managed
C++ and call the unmanaged code directly.

That said, if you're seeing a performance issue in C#, you're likely to
see the same thing in managed C++ AFAIK. There are some differences in
specific compiler optimizations, but I'd guess that the big hits,
involving transitions to OS components, are going to be the same since
the managed C++ is running using the CLR just like C#.
Basically I think I can get away with just using unsafe code to work with
the buffers. I'm mainly worried about the performance hit associated with
doing this. From my initial tests C# is anywhere from 2-5 times slower at
calling kernel mode drivers than unmanaged C++(not sure if I can get any
speed up by indirectly referencing unamanged C++ though so I might take that
hit no matter what if I plan on using C#).

As I mention above, I'd guess you'll get that hit regardless of
language, as long as you are using managed code. Are you saying that
the cost of the call itself is 2-5 times slower? Or are you saying that
overall performance is that much slower?

If the former, 2X seem reasonable, 5X is surprising but believable. If
you're talking about overall performance, then it seems like either all
you're doing is making those calls, or there's something odd about the
measuring. I'm hoping it's the former, in which case while the
difference may be dramatic, I'm not sure it's a reason to avoid managed
code or even to worry about it.

It's really overall performance you care about, and it's not uncommon at
all to find individual sections of code that are much slower, but which
don't affect overall performance much because they aren't executed very
often relative to the other code.

Pete
 
W

Willy Denoyette [MVP]

Jon Slaughter said:
How difficult is it for one to integrate unmanaged C++ into C#? I know for
functions one can use DLLimport but how does one go about doing it for
classes? Do I have to completely reimplement the classes in managed C++ as
a wrapper to the unmanaged C++ classes or is there an easier way?

C++ classes cannot be used directly from C#, only pure C functions can be
called through the PInvoke layer.
The only way you can create instances of unmanaged C++ is by wrapping these
classes by a managed class that delegates the operations on the unmanaged
class.
Essentially what I have done is written a C++ kernel mode driver and I
want to use it from my C# program. Because it requires some setup outside
the kernel(because it has to pass buffers back and forth and extract the
information out of the buffers) I'd rather keep the that specific code
unmanaged because its probably slightly faster.
Not necessarely, keep in mind that you are adding a layer and as such you
are extending the path to the final code.
..
But I don't want to have a huge number of dll imports and write a C#
wrapper class over each of the imports because it seems a little
excessive. (Not only does the driver internally use a similar class but
I'd essentially be implementing the same class 3 times... one in the
driver, which is actually slightly different but pretty much with same
interface, one in unmanaged C++ to interface with the driver, and some
type of managed wrapper.)

Is there a better way? Can I just mix unmanaged and managed C++ in the
same project to do all the work and not have to end up with a C# wrapper?

Yep, you can have the wrapper and the native code in one project, even in
the same assembly. C++/CLI can mix native and managed code in a single DLL.
Basically I think I can get away with just using unsafe code to work with
the buffers. I'm mainly worried about the performance hit associated with
doing this. From my initial tests C# is anywhere from 2-5 times slower at
calling kernel mode drivers than unmanaged C++(not sure if I can get any
speed up by indirectly referencing unamanged C++ though so I might take
that hit no matter what if I plan on using C#). Of course I don't want to
end up with having to change 3 classes every time I make a simple change
either.

2-5 times? How did you compile the CS module, how did you declare the
PInvoke signature (DllImport), what function are you actually calling, what
are you measuring and how did you measure this?

The first time you call into unmanaged from managed you'll incur a serious
call overhead, this is because the CLR has to synthesize and JIT a
(marshaling) thunk, but once the thunk is created the overhead is very low,
all depends on the argument types, the number of arguments and the security
attribute set on the invoked function.
For instance, calling a function that takes no or only blittable type
arguments and which has the SuppressUnmanagedCodeSecurity attribute set [1],
the overhead is only 4 instructions. This is the minimal overhead taken to
signal the GC that the thread has transitioned into unmanaged or returned
from unmanaged.
Functions that take arrays or structures of blit-able types only, take an
overhead of ~50 instructions, while functions that take string arguments
[3], incur the highest overhead 50-xxx instructions depending on the type
unmanaged char (wide char or MBCS), the reason for this is that the
marshaler needs to convert the managed String representation into the
unmanaged char or wchar_t representation.

[1] 4 instructions overhead
[DllImport("lib.dll"), SuppressUnmanagedCodeSecurity] extern static int
F(int i);

[2] ~50 instructions overhead
[DllImport("lib.dll"), SuppressUnmanagedCodeSecurity] extern static void
F(int[] ia);

[3] ~55instructions overhead
[DllImport("lib.dll"), SuppressUnmanagedCodeSecurity] extern static int
FS([MarshalAs(UnmanagedType.LPWStr)] string s);
extern "C" __declspec(dllexport) int __stdcall FS(wchar_t *s){....}

a minimum of several hundred instruction depending on the string length.
[DllImport("lib.dll"), SuppressUnmanagedCodeSecurity] extern static int
FS(string s);
extern "C" __declspec(dllexport) int __stdcall FS(char *s){....}

The managed/unmanaged transition is low when compared to a kernel transition
(+ 4000 instruction), add to that that you will probably execute several
thousands instruction in the driver, and it becomes apparent that the
managed/unmanaged overhead becomes negligible. After all, this is the
overhead the you'll take when using the IO, Socket etc... classes from
managed code. Performing disk IO from managed code is not measurable slower
than from unmanaged code.

Willy.
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Peter said:
I don't know the specifics, but my impression was that you can DllImport
C++ classes, COM, etc. in similar ways to doing it for individual
functions.

C functions can be called as DllImport'ed.

COM classes (C++ or other) can be referenced directly (not quite but
..NET creates all the necessary stuff behind the scene).

C++ classes can not be used dierectly.
I personally don't find p/invoke (DllImport) all that easy, mainly
because MSDN doesn't seem to have any really good, easily-navigated and
thorough documentation on the topic. You know the docs are lacking when
the most common reference is a 3rd-party site. In this case,
http://www.pinvoke.net/ is the one that seems to come up a lot more often.

You might want to start there. I don't know how long they've had this,
but I just noticed they have a VS add-in that is supposed to make it
easy to add DllImport signatures to your project. It's mentioned on the
front page. Looks like it could be an incredible time-saver.

Of course. Just as you could call unmanaged code from managed C++ to
create your own wrapper, you could just implement everything in managed
C++ and call the unmanaged code directly.

Managed C++ in the middle is 100 times better than starting to fiddle
with C++ name mangled names in DllImport's.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top