1

変更できないネイティブ C++ dll の周りに CLI/C++ ラッパーを作成しています。ネイティブ DLL の関数の 1 つは、アンマネージ オブジェクトのベクトルを返します。このベクトルを CLI ラッパーでラップする最良の方法は何でしょうか? CLI ラッパーは、C# アプリケーションで使用されます。

class __declspec(dllexport) Instrument
{
  public:
        Instrument();
        ~Instrument();
        string _type;
        unsigned int _depth;
}

ネイティブ DLL には、ラップしようとしている関数 getInstruments() があります

 class __declspec(dllexport) InstrumentList
   {
       InstrumentList();
       ~InstrumentList();
       vector<Instrument*> getInstruments();
   }

そのため、instrument クラスをマネージド クラスでラップし、InstrumentList クラスをマネージド クラスでラップする必要があります。Instrument クラスをラップしましたが、getInstruments() によって返されたベクトルを、InstrumentList の CLI ラッパーが返すことができる同等のものに変換する必要があります。

4

2 に答える 2

4

InstrumentList をまったくラップしたくない場合があります。

ストック .NET コレクション (C++/CLI からアクセス可能) の 1 つを使用して、Instrument ラッパーのコレクションを作成するだけです。コレクションにデータバインドしたいので、 ObservableCollection を使用しています。

例:

public ref class MyManagedType
{
    public:
        MyManagedType(MyNativeType* pObject) { m_pObject = pObject };

    private:
        MyNativeType* m_pObject;
}

次に、次のようにマネージド コレクションを作成します。

ObservableCollection<MyManagedType^>^ managedCollection = gcnew ObservableCollection<MyManagedType^>();

最後に、オブジェクトをコレクションに追加します。

managedCollection->Add(gcnew MyManagedType(pNativeObject));

ネイティブ コレクションとマネージド コレクションの同期を維持するのは少し手間がかかりますが、うまく機能します。

于 2011-05-19T20:37:20.297 に答える
4

Instrument::_typeマネージド ファサードにアクセスするまでのマーシャリングを遅らせたい場合を除き、次のようにして開始します。

public ref class InstrumentM
{
    String^ _type;
    unsigned _depth;

internal:
    explicit InstrumentM(Instrument const& i)
      : _type(gcnew String(i._type.c_str())),
        _depth(i._depth)
    { }

public:
    property String^ Type { String^ get() { return _type; } }
    property unsigned Depth { unsigned get() { return _depth; } }
};

public ref class InstrumentListM
{
    InstrumentList* _list;

public:
    InstrumentListM() : _list(new InstrumentList()) { }
    ~InstrumentListM() { this->!InstrumentListM(); }
    !InstrumentListM()
    {
        delete _list;
        _list = nullptr;
    }

    array<InstrumentM^>^ GetInstruments()
    {
        if (!_list)
            throw gcnew ObjectDisposedException(L"_list");

        vector<Instrument*> const& v = _list->getInstruments();
        array<InstrumentM^>^ ret = gcnew array<InstrumentM^>(v.size());
        for (int i = 0, i_max = ret->Length; i != i_max; ++i)
            if (v[i])
                ret[i] = gcnew InstrumentM(*v[i])
        return ret;
    }
};
于 2011-05-19T20:43:38.417 に答える