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?)
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, ...);
}
};
}
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));
}
};
精彩评论