【问题标题】:Python ctypes, dll function argumentsPython ctypes,dll函数参数
【发布时间】:2019-02-21 21:55:13
【问题描述】:

我有一个带有函数的 DLL

EXPORT long Util_funct( char *intext, char *outtext, int *outlen )

看起来它需要 char *intext、char *outtext、int *outlen。 我试图在 python 中定义不同的数据类型,所以我可以传递一个参数,但到目前为止没有成功。

from ctypes import *

string1 = "testrr"
#b_string1 = string1.encode('utf-8')

dll = WinDLL('util.dll')
funct = dll.Util_funct

funct.argtypes = [c_wchar_p,c_char_p, POINTER(c_int)]
funct.restype = c_char_p

p = c_int()
buf = create_string_buffer(1024)
retval = funct(string1, buf, byref(p))

print(retval)

输出为无,但我看到p 发生了一些变化。 你能帮我为函数定义正确的数据类型吗?

【问题讨论】:

  • 返回类型(restype)是c_long,而不是c_char_p
  • 如果您的函数需要一个可变缓冲区,您可能还需要使用string1 = create_string_buffer('testrr') 而不是string1 = 'testrr'

标签: python dll ctypes


【解决方案1】:

这应该可行:

from ctypes import *

string1 = b'testrr'     # byte string for char*

dll = CDLL('util.dll')  # CDLL unless function declared __stdcall
funct = dll.Util_funct

funct.argtypes = c_char_p,c_char_p,POINTER(c_int) # c_char_p for char*
funct.restype = c_long # return value is long

p = c_int()
buf = create_string_buffer(1024) # assume this is big enough???
retval = funct(string1, buf, byref(p))

print(retval)

【讨论】:

  • 谢谢!这将返回 0。同时,如果这有助于定义正确的数据类型,我发现该函数在 C# 中的用法int l);` 我的理解是第一部分是输入,第二部分是缓冲区和第三种指针,函数接收一个字符串并应该返回编码的字符串。请让我知道这是否有意义。
  • @user11098401 这是有道理的。查看buf.valuep.value 以查看返回的字符串和长度。
  • p.value 我得到了 6,如果我更改 string1,它会改变,对应于字符数。从 buf.value 我得到了 b'\x9d\xf93\x8d5\x90',它也依赖于 string1。不确定如何在输出中获取字符串?
  • @user110988401 看起来该函数以某种方式加密了输入字符串,因此看起来也正确。该函数采用字节字符串。您提供的“答案”是错误的。 c_wchar_p 是函数输入的错误类型。
【解决方案2】:

感谢您的所有回答! 我想我想通了。使用不是最聪明的方法,而只是尝试/试验不同的数据类型。 由于这不是一个通用库,而且我没有它的信息,也许这个解决方案对其他人来说不会很有用,但无论如何。

看起来函数一次只处理一个字符,因为如果我传递一个单词,它只返回一个编码字符。 所以这里是:

from ctypes import *


buf = create_unicode_buffer(1024)
string1 = "a"
c_s = c_wchar_p(string1)

dll = CDLL('util.dll')
enc = dll.Util_funct

enc.argtypes = c_wchar_p, c_wchar_p, POINTER(c_int)

enc.restype = c_long # i don't think this type matters at all

p = c_int()


enc(c_s, buf, byref(p))


print(p.value)
print(buf.value)

输出为 1 和符号 ^

再次感谢

【讨论】:

  • 你得到了一个字符,因为 c_wchar_p 是错误的类型。
  • @MarkTolonen 我的印象是 c_wchar 是单字符,c_wchar_p 是字符串。
  • 不,c_wchar 是单个宽字符,取决于 C 编译器是 16 位还是 32 位宽。 C 等效项是wchar_tc_wchar_p 是一个宽字符串(C wchar_t*)。对于带有char* 输入的C 函数,您需要c_char_p,它是一个Python byte 字符串。以b'abcd' 为例。
猜你喜欢
  • 1970-01-01
  • 2021-11-17
  • 2016-01-28
  • 1970-01-01
  • 2011-03-30
  • 2013-11-25
  • 1970-01-01
  • 2020-07-30
  • 2021-11-03
相关资源
最近更新 更多