将C#链接到C ++应用程序 [英] Linking C# to C++ applications

查看:71
本文介绍了将C#链接到C ++应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将c ++ MFC应用程序链接到我的C#应用​​程序.问题是C ++应用程序没有任何dll或lib.它使用静态库.

I''m trying to link a c++ MFC application to my C# app. The problem is the C++ app doesn''t have any dll''s or a lib. It uses a static library. Is there any other way to link the two applications without having to tear apart one and add it to the other?

推荐答案

您需要哪种链接?您可以在C#项目中使用C ++库,但是在C ++项目中使用C#库要困难得多,因此许多人甚至认为这是不可能的.第二种方法相当先进,希望您能避免.首先学习第一个,然后对第二个问是否有兴趣.

那么,如何在C#中使用C ++代码?当然,您需要使C ++代码成为DLL.如果没关系实现使用静态库,但是您的C ++项目应该创建DLL并通过导出它们来暴露一些功能.您应该使用原始类型或结构,但不能使用C ++类.也可以通过.NET使用C ++类来公开C ++类,但这是高级主题,您可以单独询问它.

从这一刻起,您可以在C#项目中链接本机DLL的方法.在每种情况下,您都将需要DLL文件的名称和导出方法的签名.该技术称为 P/调用.

您需要使用默认的 Marshalling 使用在C#中实现的可用类型映射将C ++签名转换为C#签名.在更困难的情况下,您需要使用[MarshalAs]属性.在更困难的情况下,您可能需要创建自定义封送处理.

了解有关P/Invoke的信息:
http://en.wikipedia.org/wiki/PInvoke [ http://msdn.microsoft.com/en-us/library/Aa712982 [ ^ ].

阅读此CodeProject文章:基本P/调用 [
What kind of link do you need? You can use your C++ library in C# project, but using C# library in C++ project is much more difficult so many even think it is impossible. Second way is quite advanced and I hope you can avoid it; first learn a first one and later ask a question on the second one if interested.

So, how to use C++ code in C#? Of course, you need to make you C++ code a DLL. If does not matter of implementation uses static library, but your C++ project should create DLL and expose some functions by exporting them. You should use primitive types or structures, but not C++ classes. Exposing C++ classes the way it can be used by .NET is also possible, but this is advanced topic, you can ask about it separately.

From this moment, you can link the methods of your native DLL in your C# project. In each case, you will need the name of DLL file and the signature of your exported methods. The technique is called P/Invoke.

You need to translate C++ signature in C# signature using available type mapping implemented in C# using default Marshalling. In more difficult cases, you need to use [MarshalAs] attribute; in even more difficult cases you might need to create custom marshaling.

Learn about P/Invoke:
http://en.wikipedia.org/wiki/PInvoke[^],
http://msdn.microsoft.com/en-us/library/Aa712982[^].

Read this CodeProject article: Essential P/Invoke[^].

—SA


这篇关于将C#链接到C ++应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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