Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wrap a C++ interface (abstract class) in C++/CLI?

I have some C++ code:

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

that I need to call from C#.
Therefore I want to wrap this C++ code in C++/CLI.

I understand how to wrap the compute() function, but how do I wrap the IProgress interface?

(It seems it is not possible for a .Net class to inherit a C++ class?)

like image 675
Andy Avatar asked Jun 27 '11 07:06

Andy


2 Answers

Use a ref class which holds a pointer to the wrapped instance:

namespace ComputeCLI {
    public ref class IProgressCB{
    public:
        void progress(int percentCompleted)
        {
            // call corresponding function of the wrapped object
            m_wrappedObject->progress(percentCompleted);
        }

    internal:
       // Create the wrapper and assign the wrapped object
       IProgressCB(Compute::IProgressCB* wrappedObject) 
            : m_wrappedObject(wrappedObject){}

        // The wrapped object
        Compute::IProgressCB* m_wrappedObject;
    };

    public ref class StaticFunctions{
    public:
        static double compute(IProgressCB^ progressCB, ...){
            Compute::compute(progressCB->m_wrappedObject, ...);
        }
    };
}
like image 186
Stephan Avatar answered Oct 28 '22 16:10

Stephan


This framework should get you started:

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));
     }
};
like image 32
Ben Voigt Avatar answered Oct 28 '22 16:10

Ben Voigt