有没有最佳实践访问C ++本机COM函数从C#互操作? [英] Is there a best practice for accessing C++ native COM functions to interop from C#?

查看:111
本文介绍了有没有最佳实践访问C ++本机COM函数从C#互操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有最佳实践来访问C ++本地COM函数以从C#互操作?

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

例如,如果我有100个C ++方法

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

我想在C#中为这些C ++方法创建一个包装器,所以我新雇的员工可以使用它而不是C ++等。C ++代码是遗留的并且吓唬我,所以我想处理它只有一次。这里的方法是否为每个方法都有一个相应的C#方法?事实上,有没有另一种方式这样做?

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.?

推荐答案

如果你的C ++方法在一个COM对象中,那么你可以使用C#的COM互操作。有关详细介绍,请参见 CLR内外:COM Interop简介

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.

如果这些C ++方法更像传统的API调用,那么你将需要使用Platform Invoke(即PInvoke)。这需要在C#中为非托管(C ++函数)创建托管原型。开始的好地方是平台调用教程

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.

就性能考虑而言,通常不会有太多的担心。从C#调用可能比从C ++直接调用慢,主要是由于编组数据。除非你调用的代码在一个关键的循环,你不会注意到任何差异。

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.

这篇关于有没有最佳实践访问C ++本机COM函数从C#互操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆