Is there a best practice for accessing C++ native

2019-04-15 02:51发布

问题:

Is there a best practice for accessing C++ native COM functions to interop from C#?

For example, if I have 100 C++ methods (basically a native library) that interacts with a core window component.

I want to basically make a wrapper for these C++ methods in C#, so all my newly hired employees can use that instead of C++, etc. The C++ code is legacy and scares me, so I want to deal with it just once. Is the approach here for each method to have a corresponding C# method? In fact, is there another way of doing this?

Can I have some sort of wrapper subsystem. How do you people generally do this?

Also, are there any performance considerations, etc.?

回答1:

If your C++ methods are in a COM object, then you can use COM interop from C#. See CLR Inside Out: Introduction to COM Interop for a good introduction.

If those C++ methods are more like traditional API calls, then you'll want to use Platform Invoke (i.e. PInvoke). That entails creating managed prototypes in C# for the unmanaged (C++ functions). A good place to start is the Platform Invoke Tutorial.

As far as performance considerations go, there typically won't be much to worry about. Calling from C# might be fractionally slower than calling directly from C++, in large part due to marshaling data. Unless the code you're calling is in a critical loop, you're not going to notice any difference.

It really depends on what those native functions do. The more you have to share data between the unmanaged and managed worlds, the more difficult the process becomes. Without more information about your specific functions, it's difficult to say where you might encounter problems.



回答2:

Use COM Interop to wrap the library. Then you can more or less treat the C++ code as .NET native code that can be called in the normal fashion.