c# - 可以从 C# 调用 C++ 代码吗?

标签 c# .net c++ unmanaged managed

是否可以从 .NET 语言(如 C#)中调用可能编译为代码库文件 (.dll) 的 C++ 代码?

特别是 C++ 代码,例如 RakNet 网络库。

最佳答案

调用 C++ 的一种简单方法是在 C++/CLI 中创建包装程序集。在 C++/CLI 中,您可以像编写 native 代码一样调用非托管代码,但您可以从 C# 调用 C++/CLI 代码,就好像它是用 C# 编写的一样。该语言基本上被设计为与现有库的互操作,作为其“ killer 级应用”。

例如 - 使用/clr 开关编译它

#include "NativeType.h"

public ref class ManagedType
{
     NativeType*   NativePtr; 

public:
     ManagedType() : NativePtr(new NativeType()) {}
     ~ManagedType() { delete NativePtr; }

     void ManagedMethod()
      { NativePtr->NativeMethod(); } 
}; 

然后在 C# 中,添加对 ManagedType 程序集的引用,并像这样使用它:

ManagedType mt = new ManagedType();
mt.ManagedMethod();

查看 this blog post一个更解释的例子。

关于c# - 可以从 C# 调用 C++ 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/935664/

相关文章:

c# - Asp.NET MVC Razor 十进制格式?到 #。###,##

.net - 在 delphi 中使用 COM DLL - MSVCR80D.dll 错误中的访问冲突

c# - WPF - 如何使用键(如字典)实现 ObservableCollection<K,T>?

c++ - 打印 curl 请求

c# - 在 LINQ 查询中使用 Expression<Func<>>

c# - 是否可以强制基于DependencyProperty的绑定(bind)以编程方式重新评估?

c# - Silverlight:如何在设置 DataContext 属性后强制绑定(bind)

c++ - 为什么这个质数每次都重复

C++。如何从函数写入文件

C# 套接字与管道