本机 C++ 的 C++/CLI 包装器用作 C# 中的参考 [英] C++/CLI wrapper for native C++ to use as reference in C#

查看:29
本文介绍了本机 C++ 的 C++/CLI 包装器用作 C# 中的参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题解释.我有我正在为其编写 C++/CLI 包装器的本机 C++ dll,它们将作为参考导入到 C# 中.

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# 中我看不到包装器中的类(从 DLL 导入).

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

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

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

推荐答案

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

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

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

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

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

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

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

#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) 在 C# 项目中添加对 C++/CLI 项目的引用.

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

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

4) Use the wrapper type within a using statement:

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

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

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.

这篇关于本机 C++ 的 C++/CLI 包装器用作 C# 中的参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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