2015-04-29 80 views
1

我想为我的python项目使用DLL(ImageSearch.dll)。它最初是为autoit开发的。 这里是AU3文件:使用DLL与python和ctypes

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 

所以我尝试使用ctypes的,但我有问题,得到变量“结果”。的确,在下面的脚本中,searchReturn的值是c_char_p(b'0'),而对于autoit脚本,我有一个字符串'|'在里面。

from ctypes import * 

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

print(searchReturn) 

我也尝试传递参数与c_int等,它会导致同样的问题。如果我不使用c_char_p(),我有一个int。我不明白为什么我得到一个int,标题显示它应该返回一个str。

+0

“我有问题”和“它不工作”也没有什么帮助。请描述这些问题,以及当它不起作用时会发生什么。 – cdarke

+0

我把更多的细节,对不起。 – Maxline

+0

是用C/C++还是类似C#编写的DLL?其中一个问题是调用约定。 'windll'使用'stdcall'调用约定,'cdll'使用'cdecl',C和C++调用约定。调用约定涉及参数顺序和堆栈清除。复杂的是C和C++可以在Windows上使用任何调用约定,您必须知道使用它。你真的需要类型的C等价物。 – cdarke

回答

1

好吧我认为我应该使用CDL但经过多次尝试并以好的方式定义参数后,我解决了我的问题。谢谢cdarke的帮助:)

下面是最终脚本:

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

好!我看到这个之前写了我的评论。 – cdarke