如何导入和使用非托管C ++类从C#? [英] How to import and use a unmanaged C++ class from C#?

查看:131
本文介绍了如何导入和使用非托管C ++类从C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个本地C ++的dll,一些头文件和导入库。 ?有没有办法如何实例是在DLL中定义的C#中的对象



这两种方式我所知道的是:




  1. 来包裹C ++代码到COM

  2. 要使用的DllImport和外部的C函数


解决方案

C ++ / CLI是你的朋友这一点。你虽然碰到一个问题:这是不可能保存C ++ / CLI ref或价值类中的标准C ++对象(那些为.NET)。所以你必须诉诸于下面的类(可以修改),我在生产中使用的代码:

 的#pragma一旦
&#包括LT;升压/ shared_ptr.hpp>

:模板LT; typename的T>
引用类句柄
{
的boost :: shared_ptr的< T> * T;

手柄()
{
如果
{
删除牛逼!(T = nullptr!);
T = nullptr;
}
}

〜手柄(){这个 - >!手柄(); }

公众:
手柄():T(新的boost :: shared_ptr的< T>((T *)0)){}

拉手%运营商=(T * p)
{
如果(p值=叔>!得到())叔>复位(对);
返回*这一点;
}

静态T *运营商及(拉手%H){返回h.t->获得(); }
静态的boost :: shared_ptr的< T>操作符>(处理H%){返回* H.T; }

T&安培;引用(){返回*&T- GT;获得(); } $ B $(B T)const的&安培;为const_reference(){返回*&T- GT;获得(); }
};



用法:处理< MyCppClass> ^手柄; 一个C ++ / CLI类中。然后您可以实现存根方法,将其转发到处理成员。垃圾收集的对象将调用C ++类实例的析构函数当且仅当没有更多的指针指向它:

 公共文献类Foo 
{
无效巴(){把手型>巴(); }

内部:
手柄< CppNamespace ::美孚> ^手柄;
};


I have an native C++ dll, some header files and the import library. Is there a way how to instantiate an object within C# that is defined in the dll?

The two ways I'm aware of are:

  1. to wrap the C++ code into COM
  2. to use DLLImport and external C functions

解决方案

C++/CLI is your friend for this. You'll run into one problem though: it is not possible to store standard C++ objects inside C++/CLI ref or value classes (the ones for .NET). So you'll have to resort to the following class (that you can modify) that I use in production code:

#pragma once
#include <boost/shared_ptr.hpp>

template <typename T>
ref class Handle
{
    boost::shared_ptr<T>* t;

    !Handle() 
    {
        if (t != nullptr)
        {
            delete t;
            t = nullptr;
        }
    }

    ~Handle() { this->!Handle(); }

public:
    Handle() : t(new boost::shared_ptr<T>((T*)0)) {}

    Handle% operator=(T* p)
    {
        if (p != t->get()) t->reset(p);
        return *this;
    }

    static T* operator&(Handle% h) { return h.t->get(); }
    static boost::shared_ptr<T> operator->(Handle% h) { return *h.t; }

    T& reference() { return *t->get(); }
    T const& const_reference() { return *t->get(); }
};

Usage: Handle<MyCppClass>^ handle; inside a C++/CLI class. You then implement stub methods, forwarding them to the handle member. Garbage collected objects will call destructors of the C++ class instance iff there is no more pointer to it:

public ref class Foo
{
    void bar() { handle->bar(); }

internal:
    Handle<CppNamespace::Foo>^ handle;
};

这篇关于如何导入和使用非托管C ++类从C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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