Problem with calling function from dll

Duncan Booth duncan.booth at invalid.invalid
Thu Dec 13 11:01:52 CET 2012


deepblu at poczta.fm wrote:

> I have problem with using function from dll.
> 
> import ctypes
> 
> b = ctypes.windll.LoadLibrary("kernel32")
> 
> a = ""
> 
> b.GetComputerNameA(a,20)
> 
> 
> But I got exception:
> 
> Traceback (most recent call last):
>   File "<pyshell#323>", line 1, in <module>
>     b.GetComputerNameA(a,20)
> WindowsError: exception: access violation reading 0x00000014
> 
> Even when I write:
> a = ctypes.c_char_p('.' * 20)
> I got the same result.
> 
> Here I found this function description:
> http://sd2cx1.webring.org/l/rd?ring=pbring;id=15;url=http%3A%2F%
2Fwww.a
> stercity.net%2F~azakrze3%2Fhtml%2Fwin32_api_functios.html 
> 
> 
> Please help.

You have to allocate a buffer for the result, and the second parameter 
is a pointer to the length of the buffer on input and contains the 
length of the result on output.

#!python2.7

from ctypes import windll, c_wchar_p, POINTER, c_int, 
create_unicode_buffer
kernel32 = windll.LoadLibrary("kernel32")
_GetComputerNameW = kernel32.GetComputerNameW
_GetComputerNameW.argtypes = [c_wchar_p, POINTER(c_int)]
_GetComputerNameW.restype = c_int

def GetComputerName():
    buf = create_unicode_buffer(255)
    len = c_int(255)
    if not _GetComputerNameW(buf, len):
        raise RuntimeError("Failed to get computer name")
    return buf.value[:len.value]

print GetComputerName()


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list