0

Hi everyone i've created a DLL in c++ and i'm using it in C# like:

[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);

Everything works fine but this function i'm calling in BackgroundWorker DoWork function and i'd like to stop function using code:

if(cancel)return;

In my c++ DLL where cancel is aa pointer to worker CancelationPending, but CancelationPending is a property so i can't get pointer to it like:

bool *cancel=&worker.CancelationPending;

And then send it as a argument in my function. Can anybody help me how to solve this problem? Also looking for Report Progress but not so much.

4

1 回答 1

0

You can use callback function (similar solution can be applied to 'report progress').

In your 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;
}

in C# project

    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);    
        }


    }
于 2013-05-28T17:44:04.733 回答