如何使用 Halcon HOperatorSet.SetDrawingObjectCallback

How to use Halcon HOperatorSet.SetDrawingObjectCallback

我很难找到如何使用 HOperatorSet.SetDrawingObjectCallback(HTuple drawID, HTuple drawObjectEvent, HTuple callbackFunction) (Docu) in C#, specifically the part of the callback HTuple callbackFunction. Apart from a Chinese website (Link),我找不到任何关于如何正确执行此操作的示例。该网站本身也不是直接可以找到的,那里使用的代码会引发致命异常。为了让其他人更好地了解如何使用 HOperatorSet.SetDrawingObjectCallback 方法,我决定创建这个问题并自己回答。

这里的关键是 HTuple callbackFunction 是一个指向类型 HDrawingObject.HDrawingObjectCallback 的委托的函数指针。然后这个委托链接到你正确的回调方法。回调方法包括 intptrdrawingIdwindowId 以及 string type.

这是代码片段,希望它能让你的一天更美好:

public class SomeClass
{
    public SomeClass()
    {
        DrawingObjectCallback = DrawingObjectCallbackHandler;
    }
    
    public void AddDrawingObject()
    {
        HOperatorSet.CreateDrawingObjectCircle(50, 50, 100, out var drawId);
        
        //Get the pointer to HDrawingObjectCallback which links to our handler
        var ptr = Marshal.GetFunctionPointerForDelegate(DrawingObjectCallback);
                
        //Select the events you want to listen to
        var listenTo = new HTuple("on_resize", "on_drag");
        
        //Finally call the method
        HOperatorSet.SetDrawingObjectCallback(drawId, listenTo, ptr);
        
        HOperatorSet.AttachDrawingObjectToWindow(HalconWindow.HalconID, drawId);
    }

    public HDrawingObject.HDrawingObjectCallback DrawingObjectCallback { get; }
    public void DrawingObjectCallbackHandler(IntPtr drawId, IntPtr windowHandle, string type)
    {
        int id = new HTuple(drawId);
        int windowId  = new HTuple(windowHandle);
        
        //Now you have the two Ids as integers and can work from here!
    }
}