4

我需要从 C++ 中的无人函数触发用 C++/CLI 编写的事件。

做这个的最好方式是什么?

提前致谢。

4

1 回答 1

1

我从codeproject上的一些帮助帖子中找到了一些帮助

想把它贴在这里可能对其他人有用

#include "stdafx.h"
#include "windows.h"

using namespace System;
using namespace System::Runtime::InteropServices;

class Camera
{
public:
    Camera()
    {
    }
    ~Camera(){}
    void (*test)(void);
    void OnNewCameraData();
    void StartDataAcquisition();

};

void Camera::StartDataAcquisition()
{
    int i;
    while(i<10)
    {
        test();
        i++;
        Sleep(1000);
    }

}

delegate void FunctionToCallDelegate();

ref class CameraAdapter
{
private:
  Camera *_camera;
  FunctionToCallDelegate ^_Function;
public:
    CameraAdapter(FunctionToCallDelegate ^handler)
    {
        _Function = handler;
    }
    void Init()
    {
        _camera = new Camera();
        pin_ptr<FunctionToCallDelegate^> tmp = &_Function;
        _camera->test = (void (__cdecl *)(void))(Marshal::GetFunctionPointerForDelegate(_Function).ToPointer());
        _camera->StartDataAcquisition();
    }

    ~CameraAdapter()
    {
        delete _camera;
        _camera = 0;
    }
  void OnNewCameraData()
  {
      Console::WriteLine("Received Frame \n");

  }  
};


int main(array<System::String ^> ^args)
{

    FunctionToCallDelegate ^dsi;
    dsi += gcnew FunctionToCallDelegate(gcnew CameraAdapter(dsi), &CameraAdapter::OnNewCameraData);
    CameraAdapter ^camera = gcnew CameraAdapter(dsi);
    camera->Init(); 
    Console::ReadKey();
    return 0;
}
于 2012-12-08T20:19:54.213 回答