Wrapping C callback in C++/CLI

血红的双手。 提交于 2019-12-24 11:09:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!