问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/7845979/wrapping-c-callback-in-c-cli