如何从C#导入和使用非托管C ++类?

问题描述:

我有一个原生的C ++ DLL,一些头文件和导入库。是否有一种方法如何实例化在dll中定义的C#中的对象?

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?

我知道的两种方式是:


  1. 将C ++代码封装到COM

  2. 中以使用DLLImport和外部C函数


C ++ / CLI是您的朋友。你会遇到一个问题,虽然:不可能存储标准C ++对象在C ++ / CLI ref或值类(.NET中的)。所以你必须使用我在生产代码中使用的下面的类(你可以修改):

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(); }
};

用法: Handle< MyCppClass> ^ handle; 在C ++ / CLI类中。然后实现stub方法,将它们转发到句柄成员。垃圾收集的对象将调用C ++类实例的析构函数,如果没有更多的指针:

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;
};