如何在c++本地DLL中检查BackgroundWorker CancelationPending

How to check BackgroundWorker CancelationPending in C++ native DLL

本文关键字:检查 BackgroundWorker CancelationPending DLL 本地 c++      更新时间:2023-10-16

大家好,我在c++中创建了一个DLL,我在c#中使用它,如:

[DllImport("IMDistortions.dll", CallingConvention = CallingConvention.Cdecl)]
public static unsafe extern void ProcessBarrelDistortion(byte* bytes, int stride, int width, int height, byte pixelSize, double a, double b, double c, double d);

一切都很好,但这个函数我在后台工作DoWork函数调用,我想停止函数使用代码:

if(cancel)return;

在我的c++ DLL中,取消是一个指针到工作CancelationPending,但CancelationPending是一个属性,所以我不能得到指针到它:

bool *cancel=&worker.CancelationPending;

然后将其作为参数发送到我的函数中。有人能帮我解决这个问题吗?也在寻找报告进度,但不是那么多。

您可以使用回调函数(类似的解决方案可以应用于'report progress')

在c++ .dll

//#include <iostream>
typedef bool ( *CancellationPending)();
extern "C" __declspec(dllexport) void ProcessBarrelDistortion
 (
  unsigned char* bytes, 
  int     stride, 
  int width, 
  int height, 
  unsigned char pixelSize, 
  double a, 
  double b, 
  double c, 
  double d, 
  CancellationPending cancellationPending //callback
 )
{
    bool cancellationPending = cancellationPending();
    if (cancellationPending)
    {
        return;
    }
    //std::cout << cancellationPending;
}
c#项目中的

    public delegate bool CancellationPending();
    [DllImport("YourDll.dll", CallingConvention = CallingConvention.StdCall)]
    public static unsafe extern void ProcessBarrelDistortion
    (byte* bytes, 
     int stride, 
     int width, 
     int height, 
     byte pixelSize, 
     double a, 
     double b, 
     double c, 
     double d,
     CancellationPending cancellationPending);
    static void Main(string[] args)
    {
        var bg = new BackgroundWorker {WorkerSupportsCancellation = true};
        bg.DoWork += (sender, eventArgs) =>
        {
            Console.WriteLine("Background work....");
            Thread.Sleep(10000);
        };
        bg.RunWorkerAsync();
        unsafe
        {
            ProcessBarrelDistortion(null, 0, 0, 0, 0, 0, 0, 0, 0, 
               () => bg.CancellationPending);
        }
        bg.CancelAsync();
        unsafe
        {
            ProcessBarrelDistortion(null, 0, 0, 0, 0, 0, 0, 0, 0, 
                () => bg.CancellationPending);    
        }

    }