C# 项目和 C++ 之间的交互同一解决方案中的项目
我有一个用 C++/cli 编写的 Windows 窗体应用程序。我想用一些新的表单来扩展这个应用程序,并且我想在一个单独的项目中用 C# 创建它们。
是否可以简单地将 C# 项目添加到具有 C++ 项目的解决方案中,并且两者将进行交互?通过交互,我的意思是,例如,单击 C# 项目中编写的表单上的按钮将能够调用 C++ 项目中的方法。也许以不同的方式问,C#项目中的对象可以引用c++项目中的对象吗?
I have a windows forms app written in C++/cli. I want to extend this app with some new forms and I'd like to create them in C# in a separate project.
Is it possible to simply add a C# project to a solution that has the C++ project and the two will interact? By interaction, I mean that, say, a button clicked on a form written in the c# project will be able to call methods in the c++ project. Asked perhaps in a different way, can an object in the C# project reference an object in the c++ project?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。 C++/CLI 应用程序将能够通过以下两种方式之一与 C# 应用程序交互:
如果您正在使用 CLI 扩展(从您的帖子中听起来很像),您将能够使用新的对象引用编写代码:
托管对象:
System::String^ myString
(在 C++ 中)与 C# 中的string myString
相同托管引用:
System::String% myString
相当于ref string myString
。如果您想使用 C++ 本机类型,那么您将必须使用 P/Invoke,但这是一个完全不同的类别。对于您想要执行的操作,只需添加 C++ 项目作为对 C# 项目的引用,使用托管类型在 C++ 中编写一个公开可见的类,然后进行编译。然后,您的项目应该对您为 C++ 类选择的任何命名空间中的 C# 类可见。
哦,如果您需要通过 C++ 分配托管对象,则需要使用
gcnew
而不是new
。Yes. A C++/CLI application will be able to interface with a C# application, in one of two ways:
If you are using CLI extensions (which from your post it sounds like it), you will be able to write code using the new object references:
Managed objects:
System::String^ myString
(in C++) is the same asstring myString
in C#Managed refs:
System::String% myString
is equivalent toref string myString
.If you want to use C++ native types, then you will have to use P/Invoke, but that's an entirely different category. For what you want to do, just add the C++ project as a reference to your C# project, write a publicly-visible class in C++ using managed types, and then compile. Your project should then be visible to your C# class in whatever namespace you chose for the C++ class.
Oh, and if you need to allocate managed objects through C++, you will need to use
gcnew
instead ofnew
.这可以通过使用 C++ 项目编译 dll,然后让 C# 应用程序加载该 dll,然后它将能够调用其导出的函数来完成。此方法允许您的 C++ 代码成为非托管代码。
至于查找已设置的示例,我只能找到 Visual Studio 2008 项目:Microsoft 一体化代码框架
对于 Visual Studio 2010,以下是 C++ 方面的操作方法:如何用 C++ 制作 dll
在 C++ 中使用显式 PInvoke
This can be done by compiling a dll with the C++ project, then having the C# app load that dll and then it will be able to call its exported functions. This method allows your C++ code to be unmanaged code.
As far as finding a sample that is already set up, I can only find a Visual Studio 2008 project:Microsoft All-In-One Code Framework
For visual studio 2010, here's how to do the C++ side: How to make a dll with C++
Using Explicit PInvoke in C++