Implement ImageSearchDLL.dll in C#

孤者浪人 提交于 2019-12-11 02:23:42

问题


I am trying to use ImageSearchDLL.dll in Visual Studio C#. I used to use it in AutoIt.

Following is the code I came up with to use the Imagesearch Function. However, as soon as it tried to call ImageSearch, the program crashes without any exception. I have the dll file included in my project folder. Could it be because of that although I was able to use the dll in AutoIt, it doesn't mean it would work in C# as well? Note: I tried both 32 and 64 bits of .dll

    [DllImport("ImageSearchDLL.dll")]
    static extern string ImageSearch(int aLeft, int aTop, int aRight, int aBottom, string aImageFile);

    public static int Search(String FilePath, int X1, int Y1, int X2, int Y2, ref int X, ref int Y, int tolerance, int resultPosition)
    {
        if (tolerance > 0) 
        {
            FilePath = "*" + tolerance.ToString() + " " + FilePath;
        }

        string result = ImageSearch(X1, Y1, X2, Y2, "test.png"); **<- crash here**
        string[] result_array = result.Split('|');
        if (result_array[0] == "0" )
            return 0;
        X = Convert.ToInt32(result_array[2]);
        Y = Convert.ToInt32(result_array[3]);
        if (resultPosition == 1)
        {
            X = X + (Convert.ToInt32(result_array[4]))/2;
            Y = Y + (Convert.ToInt32(result_array[5]))/2;
        }
        return 1;       
    }

回答1:


This shouldn't have to do with using C#. If the method is called with the same parameters (type and value) the DLL has to work the same way.

I used a bit different method signature than yours and it worked for me:

[DllImport("ImageSearchDLL.dll")]
        private static extern IntPtr ImageSearch(int x, int y, int right, int bottom, [MarshalAs(UnmanagedType.LPStr)]string imagePath);

Other than that, you should verify that the DLL is found and can be imported (consider using SetDLLDirectory)

[DllImport("kernel32.dll", CallingConvention = CallingConvention.Winapi)]
        public static extern bool SetDllDirectory([MarshalAs(UnmanagedType.LPStr)] String pathName);

This is how I used the ImageSearch maybe it'll help you:

public static String[] UseImageSearch(string imgPath)
{
    int right = Screen.PrimaryScreen.WorkingArea.Right;
    int bottom = Screen.PrimaryScreen.WorkingArea.Bottom;

    IntPtr result = ImageSearch(0, 0, right, bottom, imgPath);
    String res = Marshal.PtrToStringAnsi(result);

    if (res[0] == '0') return null;//not found

    String[] data = res.Split('|');
    //0->found, 1->x, 2->y, 3->image width, 4->image height;        

    // Then, you can parse it to get x and y:
    int x; int y;
    int.TryParse(data[1], out x);
    int.TryParse(data[2], out y);

    return data;
}


来源:https://stackoverflow.com/questions/22184246/implement-imagesearchdll-dll-in-c-sharp

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