Problem with calling function from dll

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Thu Dec 13 09:46:57 CET 2012


Am 13.12.2012 08:40, schrieb deepblu at poczta.fm:
> I have problem with using function from dll.
>
> import ctypes
>
> b = ctypes.windll.LoadLibrary("kernel32")
>
> a = ""
>
> b.GetComputerNameA(a,20)

GetComputerNameA takes a pointer to a writable char string. You give it 
a pointer to an immutable string. You will have to create a buffer first 
and pass that to the function. Also, I would use GetComputerNameW 
instead, although it makes little difference for this name (provided 
that's the hostname, which may only contain an ASCII subset).


> 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

Here is something else that is wrong: The address 0x00000014 that the 
function tries to access is neither the address of a mutable nor an 
immutable string but simply the value 20 that you passed as second 
parameter. In other words, the way that the parameters are passed to the 
function is wrong.


> Even when I write:
> a = ctypes.c_char_p('.' * 20)
> I got the same result.

This looks much better than passing the string above, but it still seems 
the (hopefully correct) parameters are passed wrongly.

> Here I found this function description:
> http://sd2cx1.webring.org/l/rd?ring=pbring;id=15;url=http%3A%2F%2Fwww.astercity.net%2F~azakrze3%2Fhtml%2Fwin32_api_functios.html

Use the primary source for such info:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms724295%28v=vs.85%29.aspx

One possibly important point there is the WINAPI part, which describes 
how parameters are passed to and from the function, which might be the 
only cause that this doesn't work. However, instead of try-and-error, 
rather go to the documentation of the ctypes API and search for WINAPI. 
There, you will find an example that uses a function from the win32 API, 
too. A bit further down, you will also find a create_string_buffer() 
function that could be useful for you.

http://docs.python.org/2/library/ctypes.html


Greetings!

Uli




More information about the Python-list mailing list