Vikram Ranabhatt
Vikram Ranabhatt

Reputation: 7620

Wrapping C callback in C++/CLI

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.

Upvotes: 1

Views: 1236

Answers (1)

Doc Brown
Doc Brown

Reputation: 20044

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.

Upvotes: 2

Related Questions