Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4088530
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T18:59:39+00:00 2026-05-20T18:59:39+00:00

Given the following C library with a callback event that ask to set a

  • 0

Given the following C library with a callback event that ask to set a buffer, how to write a proper C++/CLI wrapper in a type safe manner?

// The callback signature
typedef void (__cdecl *BUFFERALLOCATOR)(void *opaque, void **buffer);

// A struct that contains the context of the library
struct lib_context_base_s
{
    // The stored callback function pointer 
    BUFFERALLOCATOR buffer_allocator;
    // Opaque pointer that contain the local context. Needed in C because
    // C doesn't have closures (functions that knows the context where
    // they are defined)
    void* opaque;
};

typedef struct lib_context_base_s lib_context_base;

// Init the base context
lib_context_base* new_lib_context_base()
{
    return malloc(sizeof(lib_context_base));
}

// Free the base context
void free_lib_context_base(lib_context_base *lib_context_base)
{
    free(lib_context_base);
}

// Set the buffer allocation callback
void set_allocate_buffer_callback(lib_context_base *lib_context_base,
                                  BUFFERALLOCATOR allocate_buffer, void* opaque)
{
    lib_context_base->buffer_allocator = allocate_buffer;
    lib_context_base->opaque = opaque;
}

The library should be usable by managed code using the delegate void BufferAllocator(ref IntPtr buffer) .

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T18:59:40+00:00Added an answer on May 20, 2026 at 6:59 pm

    I will insist on type-safe principles: I know there’s already Marshal.GetFunctionPointerForDelegate but that requires function pointer type cast in C++/CLI and hides how marshalling unmanaged->managed works (debugging is much harder and I don’t like not understanding what’s happening behing the scene). Just noticed the approach is similar to this but doesn’t need a managed native class (less overhead). Please, tell me if you know how to further simplify it (mantaining type safety and marshaling control) and reduce overhead.

    The following is the C++/CLI Wrapper.h header:

    #include <gcroot.h>
    
    using namespace System;
    using namespace System::Runtime::InteropServices;
    
    namespace LibraryWrapper
    {
        // Declare the cdecl function that will be used 
        void cdecl_allocate_buffer(void *opaque, void **buffer);
    
        public ref class Library
        {
        public:
            // The BufferAllocator delegate declaration, available to any clr language
        // [In, Out] attributes needed (?) to pass the pointer as reference
            delegate void BufferAllocator([In, Out] IntPtr% buffer);
    
        internal:
            // The stored delegate ref to be used later
            BufferAllocator ^_allocate_buffer;
    
        private:
            // Native handle of the ref Library class, castable to void *
            gcroot<Library^> *_native_handle;
            // C library context
            lib_context_base *_lib_context_base;
    
        public:
            Library();
            ~Library();
            // The clr callback setter equivalent to the C counterpart, don't need
            // the context because in CLR we have closures
            void SetBufferAllocateCallback(BufferAllocator ^allocateBuffer);
        };
    }
    

    Follows C++/CLi Wrapper.cpp defines:

    #include "wrapper.h"
    
    namespace LibraryWrapper
    {
        Library::Library()
        {
            // Construct the native handle
            _native_handle = new gcroot<Library^>();
            // Initialize the library base context
            _lib_context_base = new_lib_context_base();
            // Null the _allocate_buffer delegate instance
            _allocate_buffer = nullptr;
        }
    
        Library::~Library()
        {
            free_lib_context_base(_lib_context_base);
            delete _native_handle;
        }
    
        void Library::SetBufferAllocateCallback(BufferAllocator ^allocateBuffer)
        {
            _allocate_buffer = allocateBuffer;
            // Call the C lib callback setter. Use _native_handle pointer as the opaque data 
            set_allocate_buffer_callback(_lib_context_base, cdecl_allocate_buffer,
                _native_handle);
        }
    
        void cdecl_allocate_buffer(void *opaque, void **buffer)
        {
            // Cast the opaque pointer to the hnative_handle ref (for readability)
            gcroot<Library^> & native_handle = *((gcroot<Library^>*)opaque);
            // Prepare a IntPtr wrapper to the buffer pointer
            IntPtr buffer_cli(*buffer);
            // Call the _allocate_buffer delegate in the library wrapper ref
            native_handle->_allocate_buffer(buffer_cli);
            // Set the buffer pointer to the value obtained calling the delegate
            *buffer = buffer_cli.ToPointer();
        }
    }
    

    Can be used in this way (C#):

    // Allocate a ~10mb buffer in unmanaged memory. Will be deallocated
    // automatically when buffer go out of scope
    IntPtr _buffer = Marshal.AllocHGlobal(10000000);
    
    // Init the library wrapper
    Library library = new Library();
    
    // Set the callback wrapper with an anonymous method
    library.SetBufferAllocateCallback(delegate(ref IntPtr buffer)
    {
        // Because we have closure, I can use the _buffer variable in the outer scope
        buffer = _buffer;
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there a library that can do the following?: Given an Object and a
Let's say I want to write a function that does the following: Given a
Given the following code (copied from the attoparsec library) what does the inline pragma
I want to write a following script: given a text file with the list
I am looking for XML/XHTML Java library/framework that can perform the following two tasks
Given the following classes: class Department { public String Name { get; set; }
I have the following problem: Given a Guice type literal TypeLiteral<T> template and a
Given a C API to a library controlling sessions that owns items, what is
// given following array: $data = array( 0=>array( data=>object1, col=>array( 0=>array( data=>object2, col=>array( 0=>array(
Given following array: var arr = [undefined, undefined, 2, 5, undefined, undefined]; I'd like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.