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

I have C ++ code:

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

what i need to call from c #.
So 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 the .Net class cannot inherit the C ++ class?)

+6
source share
2 answers

In this structure you should start:

 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)); } }; 
+2
source

Use a ref class that contains a pointer to a 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, ...); } }; } 
+4
source

Source: https://habr.com/ru/post/891426/


All Articles