python ctypes抛出错误?

2024-09-24 08:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

到目前为止,我得到了一个不适合python使用的DLL,类型返回:我只是不能传递参数,因为我做错了,而且我不太理解关于我应该如何做的文档。基本上,我测试的DLL中的函数名为“iptouint”。它接受一个c_char_p并返回一个c_double。在

这是我的代码:

nDll = ctypes.WinDLL('ndll.dll')

nDllProto = ctypes.WINFUNCTYPE(ctypes.c_double)
nDllInit = nDllProto(("dllInit", nDll))

nDllTestProto = ctypes.WINFUNCTYPE(ctypes.c_double,ctypes.c_char_p)
nDllTest = nDllTestProto(("iptouint",nDll),((1, "p1",0),(1, "p2",0)))

#This is the line that throws the error:
print("IP: %s" % nDllTest("12.345.67.890"))

'''
It gives me the error:
ValueError: paramflags must have the same length as argtypes
Im not sure what to do; Ive certainly played around with it to no avail.
Help is much appreciated.
Thanks.
'''

Tags: theto类型iserrorctypesdlldouble
1条回答
网友
1楼 · 发布于 2024-09-24 08:27:05

试着简单地指示ctypes它所接受的参数类型和它返回的类型:

nDll = ctypes.WinDLL('ndll.dll')
nDll.restype = ctypes.c_double
nDll.argtypes = [ctypes.c_char_p]

result = nDll.iptouint("12.345.67.890").value

不过,请考虑以下几点:

1)如果,正如名称所示,这将IPv4值sina字符串转换为无符号Int,则返回类型不是如您所说的“double”-它将是ctypes.c\u uint32

2)您的示例值不是有效的IPv4地址,不能转换为32位整数(也就是说,它作为“双精度”也没有意义,即64位浮点数),它是无效的

3)如果您只是尝试在Python中为ipv4地址设置一个无符号的32位值,那么您不需要这样做。使用纯python有很多非常易读、更简单和多平台的方法来实现这一点。例如:

^{pr2}$

更新: 在python3.x中有一个ipaddress模块- https://docs.python.org/3/library/ipaddress.html-它也可以作为python2.x的pip安装提供,它可以始终以正确的方式处理这个问题,并且可以很好地与IPv6一起工作。在

相关问题 更多 >