我有一些C++代码:

namespace Compute {
  class __declspec(dllexport) IProgressCB {
  public:
    virtual void progress(int percentCompleted) = 0;
  };
  double __declspec(dllexport) compute(IProgressCB *progressCB, ...);
}

我需要从C#调用。
因此,我想将此C++代码包装在C++/CLI中。

我了解如何包装compute()函数,
但是如何包装IProgress接口(interface)?

(似乎.Net类不可能继承C++类吗?)

最佳答案

该框架将帮助您入门:

interface class IProgressEventSink
{ ... };

class ProgressEventForwarder : IProgressEventCB
{
    gcroot<IProgressEventSink^> m_sink;
public:
    ProgressEventForwarder(IProgressEventSink^ sink) : m_sink(sink) {}

// IProgressEventCB implementation
    virtual void OnProgress( ProgressInfo info ) { m_sink->OnProgress(info.a, info.b); }
};

ref class ComputeCLI
{
     Compute* m_pimpl;
 // ...

public:
     RegisterHandler( IProgressEventSink^ sink )
     {
         // assumes Compute deletes the handler when done
         // if not, keep this pointer and delete later to avoid memory leak
         m_pimpl->RegisterHandler(new ProgressEventForwarder(sink));
     }
};

关于c# - 如何在C++/CLI中包装C++接口(interface)(抽象类)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6489902/

10-10 12:56