Python:将一个ip地址打包为一个用于DLL的ctype.c_ulong() [英] Python: packing an ip address as a ctype.c_ulong() for use with DLL
问题描述
给出以下代码:
import ctypes
ip="192.168.1.1"
thisdll = ctypes.cdll['aDLL']
thisdll.functionThatExpectsAnIP(ip)
我正确地打包这个DLL,希望它是一个c_ulong数据类型?
how can I correctly pack this for a DLL that expects it as a c_ulong datatype?
我试过使用:
ip_netFrmt = socket.inet_aton(ip)
ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt)
但是, c_ulong()
方法返回一个错误,因为它需要一个整数。
however, the c_ulong()
method returns an error because it needs an integer.
有没有办法使用 struct.pack
来完成这个?
is there a way to use struct.pack
to accomplish this?
推荐答案
inet_aton返回一串字节。这是以前是C语言界面的通用语言。
The inet_aton returns a string of bytes. This used to be the lingua franca for C-language interfaces.
这是如何将这些字节解压缩成更有用的值。 >
Here's how to unpack those bytes into a more useful value.
>>> import socket
>>> packed_n= socket.inet_aton("128.0.0.1")
>>> import struct
>>> struct.unpack( "!L", packed_n )
(2147483649L,)
>>> hex(_[0])
'0x80000001L'
此解压缩值可与ctypes的。十六进制的东西只是告诉你,解压缩的值看起来很像一个IP地址。
This unpacked value can be used with ctypes. The hex thing is just to show you that the unpacked value looks a lot like an IP address.
这篇关于Python:将一个ip地址打包为一个用于DLL的ctype.c_ulong()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!