在c#中使用非托管dll

时间:2015-10-21 13:32:09

标签: c# c++

我一直在尝试为我创建的c ++类创建一个c#包装器。我已经四处查看了如何执行此操作,但没有一个示例似乎使用类和对象。我在c ++中有以下代码:

def self.serialize_from_session(key, salt)
  (key = key.first) if key.kind_of? Array
  (key = BSON::ObjectId.from_string(key['$oid'])) if key.kind_of? Hash

  record = to_adapter.get(key)
  record if record && record.authenticatable_salt == salt
end

def self.serialize_into_session(record)
  [record.id.to_s, record.authenticatable_salt]
end

#ifndef PORTAUDIOMANAGER_H #define PORTAUDIOMANAGER_H #include "portaudio.h" #include "pa_asio.h" class PortAudioManager { public: PortAudioManager(); virtual ~PortAudioManager(); static PortAudioManager* createObject(); void openStream(); void dispose(PortAudioManager* obj); void stopStream(); typedef struct { float left_phase; float right_phase; } paTestData; private: void* stream; paTestData data; static PortAudioManager* audioManager; }; #endif 方法创建一个PortAudioManager的新对象,并将其注册到audioManager指针。 createObject方法充当析构函数(因为我认为你不能在C#中使用构造函数和析构函数)。

所以它应该如何使用就像这样:

dispose

我如何创建一个可以在c#中使用的系统? 如果您需要更多信息,请与我们联系。

1 个答案:

答案 0 :(得分:2)

创建一个新的类库项目并使用/ clr标志进行编译。鉴于上面提到的本机C ++类,添加以下C ++ / CLI类来包装您的本机类:

public ref class PortAudioManagerManaged
{
private:
    PortAudioManagerManaged(PortAudioManager* native)
        : m_native(native) { }

public:
    PortAudioManagerManaged()
        : m_native(new PortAudioManager) { }

    // = IDisposable.Dispose
    virtual ~PortAudioManagerManaged() {
        this->!PortAudioManagerManaged();
    }

    // = Object.Finalize
    !PortAudioManagerManaged() {
        delete m_native;
        m_native = nullptr;
    }

    static PortAudioManagerManaged^ CreateObject()
    {
        return gcnew PortAudioManagerManaged(PortAudioManager::createObject());
    }

    void OpenStream()
    {
        if (!m_native)
            throw gcnew System::ObjectDisposedException(GetType()->FullName);
        m_native->openStream(); 
    }

    void StopStream()
    {
        if (!m_native)
            throw gcnew System::ObjectDisposedException(GetType()->FullName);
        m_native->stopStream(); 
    }

private:
    PortAudioManager* m_native;
};

在C#项目中,添加对C ++ / CLI类库的引用。

using (PortAudioManagerManaged manager = PortAudioManagerManaged.CreateObject())
{
    manager.OpenStream();
}