简体   繁体   English

将DLL与python和ctypes一起使用

[英]Use DLL with python and ctypes

I would like to use a DLL (ImageSearch.dll) for my python project. 我想为我的python项目使用一个DLL(ImageSearch.dll)。 It was initially developped for autoit. 它最初是为自动开发的。 Here is the au3 file: 这是au3文件:

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". 因此,我尝试使用ctypes,但是在获取变量“结果”时遇到了问题。 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 '|' 确实,在以下脚本中,searchReturn的值为c_char_p(b'0'),而对于autoit脚本,我有一个带有'|'的字符串 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. 我还尝试使用c_int等传递参数,这会导致相同的问题。 If I don't use the c_char_p(), I have an int. 如果我不使用c_char_p(),那么我有一个整数。 I don't understand why I got an int, the header shows that it should return a str. 我不明白为什么要输入int,标题显示应该返回一个str。

Ok I thought I should use cdll but after many attempts and defining arguments with the good way, I solve my problem. 好的,我认为我应该使用cdll,但是经过许多尝试并以一种好的方式定义了参数之后,我解决了我的问题。 Thank you cdarke for your help :) 谢谢cdarke的帮助:)

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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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