Note that there are some explanatory texts on larger screens.

plurals
  1. POC++/CLI class wrapper for c library - callbacks
    text
    copied!<p>I am wrapping a C library using C++/CLI. The C library was designed to be used from an unmanaged C++ class. This means that the library functions accept a C++ object pointer and then provide that pointer back in callbacks. This enables the callback code to redirect requests to an appropriate event function in the calling C++ object.</p> <p>The actual functions are quite involved, so I have simplified the problem space to just a few basic items:</p> <pre><code>// C library function signature void CLibFunc(CLIBCALLBACK *callback, void *caller); // C callback signature // Second parameter is meant to point to the calling C++ object typedef int (__stdcall CLIBCALLBACK) (int param1, void *caller); // C callback implementation int CallBackImpl(int param1, void* caller) { // Need to call the ManagedCaller's EventFunction from here // ??? } // C++/CLI caller class public ref class ManagedCaller { public: void CallerFunction(void) { // Call the C library function // Need to pass some kind of this class pointer that refers to this object CLibFunc(CallBackImpl, ????); } void EventFunction(param1) { } } </code></pre> <p>Now the C library functions need to be called from a managed C++ class. Under C++/CLI, the garbage collector moves objects around in memory, so passing a simple fixed pointer to the class does not work anymore. I can solve the problem by pinning the object, but that is not recommended because it leads to memory fragmentation. It seems that another option would be to use auto_gcroot pointers, but I am fairly new to managed C++ an I am not sure how to make this work.</p> <p>Does anyone know how to make this work? What kind of pointer should be passed to the C function? How should the callback implementation redirect to the calling object's event function?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload