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 963847
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T01:44:02+00:00 2026-05-16T01:44:02+00:00

I’m writing a DLL wrapper for my C++ library, to be called from C#.

  • 0

I’m writing a DLL wrapper for my C++ library, to be called from C#. This wrapper should also have callback functions called from the library and implemented in C#. These functions have for instance std::vector<unsigned char> as output parameters. I don’t know how to make this. How do I pass a buffer of unknown size from C# to C++ via a callback function?

Let’s take this example

CallbackFunction FunctionImplementedInCSharp;

void FunctionCalledFromLib(const std::vector<unsigned char>& input, std::vector<unsigned char>& output)
{
    // Here FunctionImplementedInCSharp (C# delegate) should somehow be called
}

void RegisterFunction(CallbackFunction f)
{
    FunctionImplementedInCSharp = f;
}

How should CallbackFunction be defined and what is the code inside FunctionCalledFromLib?

One of the things that dumb me is: how do I delete a buffer created by C# inside C++ code?

  • 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-16T01:44:03+00:00Added an answer on May 16, 2026 at 1:44 am

    There are some things you should be aware of. The first is that if you are calling a .NET delegate from unmanaged code, then unless you follow some pretty narrow constraints, you will be in for pain.

    Ideally, you can create a delegate in C# pass it into managed code, marshal it into a function pointer, hold onto it for as long as you like, then call it with no ill effects. The .NET documentation says so.

    I can tell you that this is simply not true. Eventually, part of your delegate or its thunk will get garbage collected and when you call the function pointer from unmanaged code you will get sent into oblivion. I don’t care what Microsoft says, I’ve followed their prescription to the letter and watched function pointers get turned into garbage, especially in server-side code behinds.

    Given that, the most effective way to use function pointers is thus:

    • C# code calls unmanaged code, passing in delegate.
    • Unmanaged code marshals the delegate to a function pointer.
    • Unmanaged code does some work, possible calling the function pointer.
    • Unmanaged code drops all references to the function pointer.
    • Unmanaged code returns to managed code.

    Given that, suppose we have the following in C#:

    public void PerformTrick(MyManagedDelegate delegate)
    {
        APIGlue.CallIntoUnamangedCode(delegate);
    }
    

    and then in managed C++ (not C++/CLI):

    static CallIntoUnmanagedCode(MyManagedDelegate *delegate)
    {
        MyManagedDelegate __pin *pinnedDelegate = delegate;
        SOME_CALLBACK_PTR p = Marshal::GetFunctionPointerForDelegate(pinnedDelegate);
        CallDeepIntoUnmanagedCode(p); // this will call p
    }
    

    I haven’t done this recently in C++/CLI – the syntax is different – I think it ends up looking like this:

    // This is declared in a class
    static CallIntoUnamangedCode(MyManagedDelegate ^delegate)
    {
        pin_ptr<MyManagedDelegate ^> pinnedDelegate = &delegate;
        SOME_CALLBACK_PTR p = Marshal::GetFunctionPointerForDelegate(pinnedDelegate);
        CallDeepIntoUnmanagedCode(p); // This will call p
    }
    

    When you exit this routines, the pinning gets released.

    When you really, really need to have function pointers hanging around for a while before calling, I have done the following in C++/CLI:

    1. Made a hashtable that is a map from int -> delegate.
    2. Made register/unregister routines that add new delegates into the hashtable, bumping up a counter for the hash int.
    3. Made a single static unmanaged callback routine that is registered into unmanaged code with an int from the register call. When this routine is called, it calls back into managed code saying “find the delegate associated with <int> and call it on these arguments”.

    What happens is that the delegates don’t have thunks that do transitions anymore since they’re implied. They’re free to hang around in limbo being moved by the GC as needed. When they get called, the delegate will get pinned by the CLR and released as needed. I have also seen this method fail, particularly in the case of code that statically registers callbacks at the beginning of time and expects them to stay around to the end of time. I’ve seen this fail in ASP.NET code behind as well as server side code for Silverlight working through WCF. It’s rather unnerving, but the way to fix it is to refactor your API to allow late(r) binding to function calls.

    To give you an example of when this will happen – suppose you have a library that includes a function like this:

    typedef void * (*f_AllocPtr) (size_t nBytes);
    typedef void *t_AllocCookie;
    
    extern void RegisterAllocFunction(f_AllocPtr allocPtr, t_AllocCookie cookie);
    

    and the expectation is that when you call an API that allocates memory, it will be vectored off into the supplied f_AllocPtr. Believe it or not, you can write this in C#. It’s sweet:

    public IntPtr ManagedAllocMemory(long nBytes)
    {
        byte[] data = new byte[nBytes];
        GCHandle dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
        unsafe {
            fixed (byte *b = &data[0]) {
                dataPtr = new IntPtr(b);
                RegisterPointerHandleAndArray(dataPtr, dataHandle, data);
                return dataPtr;
            }
        }
    }
    

    RegisterPointerHandleAndArray stuffs the triplet away for safe keeping. That way when the corresponding free gets called, you can do this:

    public void ManagedFreeMemory(IntPtr dataPointer)
    {
        GCHandle dataHandle;
        byte[] data;
        if (TryUnregister(dataPointer, out dataHandle, out data)) {
            dataHandle.Free();
            // do anything with data?  I dunno...
        }
    }
    

    And of course this is stupid because allocated memory is now pinned in the GC heap and will fragment it to hell – but the point is that it’s doable.

    But again, I have personally seen this fail unless the actual pointers are short lived. This typically means wrapping your API, so that when you call into a routine that accomplishes a specific task, it registers callbacks, does the task, and then pulls the callbacks out.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have a text area in my form which accepts all possible characters from
Does anyone know how can I replace this 2 symbol below from the string
I have a view passing on information from a database: def serve_article(request, id): served_article
I have a bunch of posts stored in text files formatted in yaml/textile (from

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.