简体   繁体   中英

Use DLL with python and ctypes

I would like to use a DLL (ImageSearch.dll) for my python project. It was initially developped for autoit. Here is the au3 file:

Func _ImageSearchArea($findImage,$resultPosition,$x1,$y1,$right,$bottom,ByRef $x, ByRef $y, $tolerance)
    ;MsgBox(0,"asd","" & $x1 & " " & $y1 & " " & $right & " " & $bottom)
    if $tolerance>0 then $findImage = "*" & $tolerance & " " & $findImage
    $result = DllCall("ImageSearchDLL.dll","str","ImageSearch","int",$x1,"int",$y1,"int",$right,"int",$bottom,"str",$findImage)

    ; If error exit
    if $result[0]="0" then return 0

    ; Otherwise get the x,y location of the match and the size of the image to
    ; compute the centre of search
    $array = StringSplit($result[0],"|")

   $x=Int(Number($array[2]))
   $y=Int(Number($array[3]))
   if $resultPosition=1 then
      $x=$x + Int(Number($array[4])/2)
      $y=$y + Int(Number($array[5])/2)
   endif
   return 1
EndFunc

So I try to use ctypes but I have problems to get the variable "result". Indeed, in the following script, the value of searchReturn is c_char_p(b'0') whereas with the autoit script, I have a string with '|' inside it.

from ctypes import *

ImageSearchDLL = windll.LoadLibrary("ImageSearchDLL")
ImageSearch = ImageSearchDLL.ImageSearch
searchReturn = c_char_p(ImageSearch(0,0,1919,1079,'myPic.bmp'))

print(searchReturn)

I also try to pass arguments with c_int, etc. and it leads to the same problem. If I don't use the c_char_p(), I have an int. I don't understand why I got an int, the header shows that it should return a str.

Ok I thought I should use cdll but after many attempts and defining arguments with the good way, I solve my problem. Thank you cdarke for your help :)

Here is the final script :

import ctypes

dllFunc = ctypes.windll.LoadLibrary('ImageSearchDLL.dll')
dllFunc.ImageSearch.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_char_p,)
dllFunc.ImageSearch.restype = ctypes.c_char_p

_result = dllFunc.ImageSearch(0, 0, 1920, 1080, b"myPic.bmp")
print(_result.decode('utf-8'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM