1

I have a static C library where I have non static call back function. The Client program that register this callback gets Video data from camera .

Now I am writing Wrapper(DLL) for this in C++/CLI.This Wrapper Dll will be used in C# application.

How to Implement the callback in C++/CLI so that C# code can register it and gets the video data from it.

Vikram Ranabhatt
  • 7,268
  • 15
  • 70
  • 133
  • possible duplicate of [c++/cli pass (managed) delegate to unmanaged code](http://stackoverflow.com/questions/2972452/c-cli-pass-managed-delegate-to-unmanaged-code) – Hans Passant Oct 21 '11 at 07:35

1 Answers1

2

In C++/CLI, you can have static functions (with native C signature, which can work as a callback from a C library), calling managed delegates:

// MyDispatcherClass.h
#pragma once

public delegate void MyDelegateType();

public ref class MyDispatcherClass
{
public:
    static MyDelegateType^ MyDelegate;
};

static void MyCallback(/*...*/)
{
    if (MyDispatcherClass::MyDelegate != nullptr)
        MyDispatcherClass::MyDelegate(/* do some type mapping here if needed */);
}


// MyDispatcherClass.cpp: 
#include "stdafx.h"
#include "MyDispatcherClass.h"

So register MyCallback at your C library, register your C# delegate to MyDispatcherClass::MyDelegate and you are done.

Doc Brown
  • 19,739
  • 7
  • 52
  • 88
  • @ Doc Brown: How To call Delegate in C#.Can You Please give some example code for that – Vikram Ranabhatt Oct 25 '11 at 07:41
  • No clue how this ever worked - I immediately receive the error "managed type or function cannot be used in an unmanaged function", as expected. Would upvote if I could get it to work this easily... – Ray Mar 14 '18 at 18:44
  • @RayKoopa: right now, I created a C++/CLI demo project, and copied the code you can see in my answer directly from Visual Studio (there was a missing ";" until now). This compiles fine! Maybe you tried to include this managed class directly in some unmanaged code? That won't work, you will need some additional (managed) initialization code where a pointer to `MyCallback` is passed to the unmanaged class where it is going to be used. – Doc Brown Mar 14 '18 at 21:32
  • Tried it in a C++ CLI project, with managed code being on in that section... I can try later in in a fresh project, but I still don't see how this would work from pervious experiences. – Ray Mar 15 '18 at 04:58
  • @RayKoopa: I can assure you, this works fine, tried it yesterday with VS 2017 after I got your comment. I have used this technique in a bigger project since 2009, and it worked with all VS version in between. – Doc Brown Mar 15 '18 at 06:38
  • @DocBrown I realized that I use `va_arg` in that function, and that somehow prevents me from using the managed delegate. I asked a question with code here: https://stackoverflow.com/questions/49306816/va-arg-prevents-me-from-calling-a-managed-delegate-in-a-native-callback – Ray Mar 15 '18 at 18:33