本机 C++ 的 C++/CLI 包装器用作 C# 中的引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10223186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:57:03  来源:igfitidea点击:

C++/CLI wrapper for native C++ to use as reference in C#

c#c++dllc++-cli

提问by Haix64

Title explains. I have native C++ dlls that I'm writing C++/CLI wrappers for, which will in turn will be imported in C# as reference.

标题说明。我有我正在为其编写 C++/CLI 包装器的本机 C++ dll,这些 dll 反过来将作为参考导入到 C# 中。

The problem is that in C# I don't see the classes I have in wrapper (imported from DLL).

问题是在 C# 中我没有看到我在包装器中的类(从 DLL 导入)。

What keywords should I use and HOW to re-declare my native C++ objects to become visible in C#?

我应该使用哪些关键字以及如何重新声明我的本机 C++ 对象以在 C# 中可见?

采纳答案by Asik

Ok, tutorial. You have a C++ class NativeClassthat you want to expose to C#.

好的,教程。您有一个NativeClass要公开给 C#的 C++ 类。

class NativeClass { 
public:
    void Method();
};

1) Create a C++/CLI project. Link to your C++ library and headers.

1) 创建一个 C++/CLI 项目。链接到您的 C++ 库和头文件。

2) Create a wrapper class that exposes the methods you want. Example:

2)创建一个包装类来公开你想要的方法。例子:

#include "NativeClass.h"

public ref class NativeClassWrapper {
    NativeClass* m_nativeClass;

public:
    NativeClassWrapper() { m_nativeClass = new NativeClass(); }
    ~NativeClassWrapper() { this->!NativeClassWrapper(); }
    !NativeClassWrapper() { delete m_nativeClass; }
    void Method() {
        m_nativeClass->Method();
    }
};

3) Add a reference to your C++/CLI project in your C# project.

3) 在 C# 项目中添加对 C++/CLI 项目的引用。

4) Use the wrapper type within a using statement:

4)在 using 语句中使用包装器类型:

using (var nativeObject = new NativeClassWrapper()) {
    nativeObject.Method();
}

The using statement ensures Dispose() is called, which immediately runs the destructor and destroys the native object. You will otherwise have memory leaks and probably will die horribly (not you, the program). Note : The Dispose() method is magically created for you.

using 语句确保调用 Dispose(),它立即运行析构函数并销毁本机对象。否则你会出现内存泄漏,并且可能会死得很惨(不是你,程序)。注意:Dispose() 方法是为您神奇地创建的