Skip to main content
 首页 » 编程设计

python之将 Python Ctypes 用于 ssdeep 的 fuzzy.dll 但收到错误

2024年08月12日35bluestorm

我正在尝试使用 Python 和 ctypes 来使用来自 ssdeep 的 fuzzy.dll。到目前为止,我尝试的所有操作都因访问冲突错误而失败。这是我在更改到包含 fuzzy.dll 和 fuzzy.def 文件的正确目录后所做的:

>>> import os,sys 
>>> from ctypes import * 
>>> fn = create_string_buffer(os.path.abspath("fuzzy.def")) 
>>> fuzz = windll.fuzzy 
>>> chash = c_char_p(512) 
>>> hstat = fuzz.fuzzy_hash_filename(fn,chash) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
WindowsError: exception: access violation writing 0x00000200 
>>> 

据我所知,我已经传递了正确的c_types。来自 fuzzy.h:

extern int fuzzy_hash_filename(char * filename, char * result) 

我就是无法克服访问冲突。

请您参考如下方法:

您的代码有两个问题:

  1. 您不应使用 windll.fuzzy,而应使用 cdll.fuzzy -- 来自 ctypes documentation :

    cdll loads libraries which export functions using the standard cdecl calling convention, while windll libraries call functions using the stdcall calling convention.

  2. 对于返回值 (chash),您应该声明一个缓冲区而不是创建一个指向 0x0000200 (=512) 的指针——这是访问的地方违规来自。请改用 create_string_buffer('\000' * 512)。

所以你的例子应该是这样的:

>>> import os, sys 
>>> from ctypes import * 
>>> fn = create_string_buffer(os.path.abspath("fuzzy.def")) 
>>> fuzz = cdll.fuzzy 
>>> chash = create_string_buffer('\000' * 512) 
>>> hstat = fuzz.fuzzy_hash_filename(fn,chash) 
>>> print hstat 
0 # == success