Win32::API - Perl Win32 API Import Facility |
Win32::API - Perl Win32 API Import Facility
#### Method 1: with prototype
use Win32::API; $function = Win32::API::More->new( 'mydll', 'int sum_integers(int a, int b)' ); #### $^E is non-Cygwin only die "Error: $^E" if ! $function; #### or on Cygwin and non-Cygwin die "Error: ".(Win32::FormatMessage(Win32::GetLastError())) if ! $function; #### $return = $function->Call(3, 2);
#### Method 2: with prototype and your function pointer
use Win32::API; $function = Win32::API::More->new( undef, 38123456, 'int name_ignored(int a, int b)' ); die "Error: $^E" if ! $function; #$^E is non-Cygwin only $return = $function->Call(3, 2);
#### Method 3: with parameter list use Win32::API; $function = Win32::API::More->new( 'mydll', 'sum_integers', 'II', 'I' ); die "Error: $^E" if ! $function; #$^E is non-Cygwin only $return = $function->Call(3, 2); #### Method 4: with parameter list and your function pointer use Win32::API; $function = Win32::API::More->new( undef, 38123456, 'name_ignored', 'II', 'I' ); die "Error: $^E" if ! $function; #$^E is non-Cygwin only $return = $function->Call(3, 2); #### Method 5: with Import (slightly faster than ->Call) use Win32::API; $function = Win32::API::More->Import( 'mydll', 'int sum_integers(int a, int b)' ); die "Error: $^E" if ! $function; #$^E is non-Cygwin only $return = sum_integers(3, 2);
With this module you can import and call arbitrary functions from Win32's Dynamic Link Libraries (DLL) or arbitrary functions for which you have a pointer (MS COM, etc), without having to write an XS extension. Note, however, that this module can't do everything. In fact, parameters input and output is limited to simpler cases.
A regular XS extension is always safer and faster anyway.
The current version of Win32::API is always available at your nearest CPAN mirror:
http://search.cpan.org/dist/Win32-API/
A short example of how you can use this module (it just gets the PID of
the current process, eg. same as Perl's internal $$
):
use Win32::API; Win32::API::More->Import("kernel32", "int GetCurrentProcessId()"); $PID = GetCurrentProcessId();
Starting with 0.69. Win32::API initiated objects are deprecated due to numerous
bugs and improvements, use Win32::API::More now. The use statement remains
as use Win32::API;
.
The possibilities are nearly infinite (but not all are good :-). Enjoy it.
To use this module put the following line at the beginning of your script:
use Win32::API;
You can now use the new()
function of the Win32::API module to create a
new Win32::API::More object (see IMPORTING A FUNCTION) and then invoke the
Call()
method on this object to perform a call to the imported API
(see CALLING AN IMPORTED FUNCTION).
Starting from version 0.40, you can also avoid creating a Win32::API::More object
and instead automatically define a Perl sub with the same name of the API
function you're importing. This 2nd way using Import
to create a sub instead
of an object is slightly faster than doing ->Call()
. The details of the
API definitions are the same, just the method name is different:
my $GetCurrentProcessId = Win32::API::More->new( "kernel32", "int GetCurrentProcessId()" ); die "Failed to import GetCurrentProcessId" if !$GetCurrentProcessId; $GetCurrentProcessId->UseMI64(1); my $PID = $GetCurrentProcessId->Call();
#### vs.
my $UnusedGCPI = Win32::API::More->Import("kernel32", "int GetCurrentProcessId()"); die "Failed to import GetCurrentProcessId" if !$UnusedGCPI; $UnusedGCPI->UseMI64(1); $PID = GetCurrentProcessId();
Note that Import
returns the Win32::API obj on success and false on failure
(in which case you can check the content of $^E
). This allows some settings
to be set through method calls that can't be specified as a parameter to Import,
yet still have the convience of not writing ->Call()
. The Win32::API obj
does not need to be assigned to a scalar. unless(Win32::API::More->Import
is fine. Prior to v0.76_02, Import
returned returned 1 on success and 0 on
failure.
You can import a function from a 32 bit Dynamic Link Library (DLL) file with
the new()
function or, starting in 0.69, supply your own function pointer.
This will create a Perl object that contains the reference to that function,
which you can later Call()
.
What you need to know is the prototype of the function you're going to import (eg. the definition of the function expressed in C syntax).
Starting from version 0.40, there are 2 different approaches for this step: (the preferred) one uses the prototype directly, while the other (now deprecated) one uses Win32::API's internal representation for parameters.
You need to pass 2 or 3 parameters:
ERROR_NOACCESS
.
The C prototype of the function. If you are using a function pointer, the name
of the function should be something ``friendly'' to you and no attempt is made
to retrieve such a name from any DLL's export table. This name for a function
pointer is also used for Import().
When calling a function imported with a prototype, if you pass an
undefined Perl scalar to one of its arguments, it will be
automatically turned into a C NULL
value.
See the Win32::API::Type manpage for a list of the known parameter types and the Win32::API::Struct manpage for information on how to define a structure.
If a prototype type is exactly signed char
or unsigned char
for an
``in'' parameter or the return parameter, and for ``in'' parameters only
signed char *
or unsigned char *
the parameters will be treated as a
number, 0x01
, not "\x01"
. ``UCHAR'' is not ``unsigned char''. Change the
C prototype if you want numeric handling for your chars.
You need to pass at minimum 4 parameters.
1234
,
not string "\x01\x02\x03\x04"
. Undef will be returned if the pointer is not
readable, Win32::GetLastError/$^E in the perlvar manpage
will be ERROR_NOACCESS
.croak
an error message and
die
.To better explain their meaning, let's suppose that we
want to import and call the Win32 API GetTempPath()
.
This function is defined in C as:
DWORD WINAPI GetTempPathA( DWORD nBufferLength, LPSTR lpBuffer );
This is documented in the Win32 SDK Reference; you can look for it on the Microsoft's WWW site, or in your C compiler's documentation, if you own one.
When specifying this name as parameter, the .DLL extension is implicit, and if no path is given, the file is searched through a couple of directories, including:
You may, but don't have to write C:\windows\system\kernel32.dll; or kernel32.dll, only kernel32 is enough:
$GetTempPath = new Win32::API::More('kernel32', ...Since this function is from a DLL, skip the 2nd parameter. Skip does not mean supplying undef. Now for the real second parameter: the name of the function. It must be written exactly as it is exported by the library (case is significant here). If you are using Windows 95 or NT 4.0, you can use the Quick View command on the DLL file to see the function it exports. Remember that you can only import functions from 32 or 64 bit DLLs: in Quick View, the file's characteristics should report somewhere ``32 bit word machine''; as a rule of thumb, when you see that all the exported functions are in upper case, the DLL is a 16 bit one and you can't use it. You also can not load a 32 bit DLL into a 64 bit Perl, or vice versa. If you try,
new
/Import
will fail
and $^E
will be ERROR_BAD_EXE_FORMAT
.
If their capitalization looks correct, then it's probably a 32 bit
DLL. If you have Platform SDK or Visual Studio, you can use the Dumpbin
tool. Call it as dumpbin /exports name_of_dll.dll
on the command line.
If you have Mingw GCC, use objdump as
objdump -x name_of_dll.dll > dlldump.txt
and search for the word exports
in the very long output.
Also note that many Win32 APIs are exported twice, with the addition of a final A or W to their name, for - respectively - the ASCII and the Unicode version. When a function name is not found, Win32::API will actually append an A to the name and try again; if the extension is built on a Unicode system, then it will try with the W instead. So our function name will be:
$GetTempPath = new Win32::API::More('kernel32', 'GetTempPath', ...
In our case GetTempPath
is really loaded as GetTempPathA
.
"abcd" [a, b, c, d] \@LIST
But those are not:
(a, b, c, d) @LIST
The number of characters, or elements in the list, specifies the number of parameters, and each character or element specifies the type of an argument; allowed types are:
I
:
value is an unsigned integer (unsigned int)i
:
value is an signed integer (signed int or int)N
:
value is a unsigned pointer sized number (unsigned long)n
:
value is a signed pointer sized number (signed long or long)Q
:
value is a unsigned 64 bit integer number (unsigned long long, unsigned __int64)
See next item for details.q
:
value is a signed 64 bit integer number (long long, __int64)
If your perl has 'Q'/'q' quads support for pack in the perlfunc manpage then Win32::API's 'q'
is a normal perl numeric scalar. All 64 bit Perls have quad support. Almost no
32 bit Perls have quad support. On 32 bit Perls, without quad support,
Win32::API's 'q'/'Q' letter is a packed 8 byte string. So 0x8000000050000000
from a perl with native Quad support would be written as
"\x00\x00\x00\x50\x00\x00\x00\x80"
on a 32 bit Perl without Quad support.
To improve the use of 64 bit integers with Win32::API on a 32 bit Perl without
Quad support, there is a per Win32::API::* object setting called UseMI64
that causes all quads to be accepted as, and returned as the Math::Int64 manpage objects.
For ``in'' params in Win32::API and Win32::API::More and ``out'' in
Win32::API::Callback only, if the argument is a reference, it will automatically
be treated as a Math::Int64 object without having to previously call
UseMI64.F
:
value is a single precision (4 bytes) floating point number (float)D
:
value is a double precision (8 bytes) floating point number (double)S
:
value is a unsigned short (unsigned short)s
:
value is a signed short (signed short or short)C
:
value is a char (char), pass as "a"
, not 97
, "abc"
will truncate to "a"
P
:
value is a pointer (to a string, structure, etc...)
padding out the buffer string is required, buffer overflow detection is
performed. Pack and unpack the data yourself. If P is a return type, only
null terminated strings or NULL pointer are supported. If P is an in type, NULL
is integer 0
. undef
, "0"
, and ""+0
are not integer 0
, "0"+0
is
integer 0
.T
:
value is a Win32::API::Struct object, in parameter only, pass by reference
(pointer) only, pass by copy not implemented, see other sections for moreK
:
value is a Win32::API::Callback object, in parameter only, (see the Win32::API::Callback manpage)V
:
no value, no parameters, stands for void
, may not be combined with any other
letters, equivalent to a ``''For beginners, just skip this paragraph.
Note, all parameter types are little endian. This is probably what you want
unless the documentation for the C function you are calling explicitly says
the parameters must be big endian. If there is no documentation for your C
function or no mention of endianess in the documentation, this doesn't apply
to you and skip the rest of this paragraph. There is no inherent support
for big endian parameters. Perl's scalar numbers model is that numeric
scalars are effectively opaque and their machine representation is
irrelevant. On Windows Perl, scalar numbers are little endian
internally. So $number = 5; print "$number";
will put 5 on the screen.
$number
given to Win32::API will pass little endian integer 5 to the C
function call. This is almost surly what you want. If you really must pass
a big endian integer, do $number = unpack('L', pack('N', 5));
, then
print "$number";
will put 83886080 on the screen, but this is big endian 5,
and passing 83886080 to ->Call()
will make sure that
the C function is getting big endian 5. See the perlpacktut manpage for more.
Our function needs two parameters: a number (DWORD
) and a pointer to a
string (LPSTR
):
$GetTempPath = new Win32::API('kernel32', 'GetTempPath', 'NP', ...The fourth is the type of the value returned by the function. It can be one of the types seen above, plus another type named V (for
void
), used for functions that do not return a value.
In our example the value returned by GetTempPath()
is a DWORD
, which is a
typedef for unsigned long, so our return type will be N:
$GetTempPath = new Win32::API::More('kernel32', 'GetTempPath', 'NP', 'N');
Now the line is complete, and the GetTempPath()
API is ready to be used
in Perl. Before calling it, you should test that $GetTempPath is
defined in the perlfunc manpage, otherwise errors such as the function or the library could
not be loaded or the C prototype was unparsable happened, and no object was
created. If the return value is undefined, to get detailed error status, use
$^E in the perlvar manpage or Win32::GetLastError. $^E
is slower than Win32::GetLastError
and useless on Cygwin, but $^E
in
string context provides a readable description of the error. In numeric context,
$^E
is equivelent to Win32::GetLastError
. Win32::GetLastError
always
returns an integer error code. You may use
Win32::FormatMessage to convert an integer error
code to a readable description on Cygwin and Native builds of Perl.
Our definition, with error checking added, should then look like this:
$GetTempPath = new Win32::API::More('kernel32', 'GetTempPath', 'NP', 'N'); if(not defined $GetTempPath) { die "Can't import API GetTempPath: $^E\n"; }
To effectively make a call to an imported function you must use the
Call()
method on the Win32::API object you created.
Continuing with the example from the previous paragraph,
the GetTempPath()
API can be called using the method:
$GetTempPath->Call(...
Of course, parameters have to be passed as defined in the import phase.
In particular, if the number of parameters does not match (in the example,
if GetTempPath()
is called with more or less than two parameters),
Perl will croak
an error message and die
.
The two parameters needed here are the length of the buffer
that will hold the returned temporary path, and a pointer to the
buffer itself.
For numerical parameters except for char, you can use either a constant expression
or a variable, it will be numified similar to the expression ($var+0)
.
For pointers, also note that memory must be allocated before calling the function,
just like in C.
For example, to pass a buffer of 80 characters to GetTempPath(),
it must be initialized before with:
$lpBuffer = " " x 80;
This allocates a string of 80 characters. If you don't do so, you'll probably get a fatal buffer overflow error starting in 0.69. The call should therefore include:
$lpBuffer = " " x 80; $GetTempPath->Call(80, $lpBuffer);
And the result will be stored in the $lpBuffer variable.
Note that you never need to pass a reference to the variable
(eg. you don't need \$lpBuffer
), even if its value will be set
by the function.
A little problem here is that Perl does not trim the variable,
so $lpBuffer will still contain 80 characters in return; the exceeding
characters will be spaces, because we said " " x 80
.
In this case we're lucky enough, because the value returned by
the GetTempPath()
function is the length of the string, so to get
the actual temporary path we can write:
$lpBuffer = " " x 80; $return = $GetTempPath->Call(80, $lpBuffer); $TempPath = substr($lpBuffer, 0, $return);
If you don't know the length of the string, you can usually
cut it at the \0
(ASCII zero) character, which is the string
delimiter in C:
$TempPath = ((split(/\0/, $lpBuffer))[0]; # or $lpBuffer =~ s/\0.*$//;
Starting from version 0.40, Win32::API comes with a support package named Win32::API::Struct. The package is loaded automatically with Win32::API, so you don't need to use it explicitly.
With this module you can conveniently define structures and use them as parameters to Win32::API functions. A short example follows:
# the 'POINT' structure is defined in C as: # typedef struct { # LONG x; # LONG y; # } POINT;
#### define the structure Win32::API::Struct->typedef( POINT => qw{ LONG x; LONG y; }); #### import an API that uses this structure Win32::API->Import('user32', 'BOOL GetCursorPos(LPPOINT lpPoint)'); #### create a 'POINT' object my $pt = Win32::API::Struct->new('POINT'); #### call the function passing our structure object GetCursorPos($pt); #### and now, access its members print "The cursor is at: $pt->{x}, $pt->{y}\n";
Note that this works only when the function wants a pointer to a structure, not a ``pass by copy'' structure. As you can see, our structure is named 'POINT', but the API used 'LPPOINT'. Some heuristics are done to validate the argument's type vs the parameter's type if the function has a C prototype definition (not letter definition). First, if the parameter type starts with the LP prefix, the LP prefix is stripped, then compared to the argument's type. If that fails, the Win32::API::Type database (see typedef in the Win32::API::Type manpage) will be used to convert the parameter type to the base type. If that fails, the parameter type will be stripped of a trailing whitespace then a '*', and then checked against the base type. Dies if the parameter and argument types do not match after 3 attempts.
For more information, see also the Win32::API::Struct manpage.
If you don't want (or can't) use the Win32::API::Struct
facility,
you can still use the low-level approach to use structures:
$lpPoint = pack('ll', 0, 0); # store two LONGsto access the values stored in a structure, unpack() it as required:
($x, $y) = unpack(';;', $lpPoint); # get the actual values
The rest is left as an exercise to the reader...
$copy_of_memblock = ReadMemory($SourcePtr, $length);
Reads the source pointer for $length
number of bytes. Returns a copy of
the memory block in a scalar. No readability checking is done on $SourcePtr
.
$SourcePtr
's format is 123456, not "\x01\x02\x03\x04"
.
WriteMemory($DestPtr, $sourceScalar, $length);
Copies the string contents of the $sourceScalar
scalar to $DestPtr
for
$length
bytes. $length must be less than or equal to the length of
$sourceScalar
, otherwise the function croaks. No readability checking is
done on $DestPtr
. $DestPtr
's format is 123456, not
"\x01\x02\x03\x04"
. Returns nothing.
MoveMemory($destPtr, $sourcePtr, $length);
Copies a block of memory from one location to another. The source and
destination blocks may overlap. All pointers are in the format of 123456,
not "\x01\x02\x03\x04"
. No readability checking is done. Returns nothing.
if(IsBadReadPtr($ptr, $length)) {die "bad ptr";}
Probes a memory block for $length
bytes for readability. Returns true if
access violation occurs, otherwise false is returned. This function is useful
to avoid dereferencing pointers which will crash the perl process. This function
has many limitations, including not detecting uninitialized memory, not
detecting freed memory, and not detecting gibberish. It can not tell whether a
function pointer is valid x86 machine code. Ideally, you should never use it,
or remove it once your code is stable. $ptr
is in the format of 123456,
not "\x01\x02\x03\x04"
. See MS's documentation for a lot more
on this function of the same name.
$source = Encode::encode("UTF-16LE","Just another perl h\x{00E2}cker\x00"); $string = SafeReadWideCString(unpack('J',pack('p', $source))); die "impossible" if $source ne "Just another perl h\x{00E2}cker";
Safely (SEH aware) reads a utf-16 wide null terminated string (the first and
only parameter), into a scalar. Returns undef, if an access violation happens
or null pointer (same thing). The string pointer is in the format of 123456,
not "\x01\x02\x03\x04"
. The returned scalar will be UTF8 marked if the string
can not be represented in the system's ANSI codepage. Conversion is done with
WideCharToMultiByte. Returns a 0 length scalar string if WideCharToMultiByte fails.
This function was created because pack's p letter won't read UTF16
and ReadMemory and IsBadReadPtr require an explicit length.
$obj = Win32::API::More->new([$dllname | (undef , $funcptr)], [$c_proto | ($in, $out [, $calling_convention])]);
See DESCRIPTION.
See DESCRIPTION.
The main method of a Win32::API object. Documented elsewhere in this document.
$bool = $APIObj->UseMI64(); $oldbool = $APIObj->UseMI64($newbool);
Turns on Quads as the Math::Int64 manpage objects support for a particular object
instance. You must call use in the perlfunc manpage/require in the perlfunc manpage on Math::Int64
before calling UseMI64. Win32::API does not use
Math::Int64 for you.
Works on Win32::API and Win32::API::Callback objects. This method
does not exist if your Perl natively supports Quads (64 bit Perl for example).
Takes 1 optional parameter, which is a true or false value to use or don't use
Math::Int64, returns the old setting, which is a true or false value. If called
without any parameters, returns current setting, which is a true or false value,
without setting the option. As discussed in q, if you are not using
Math::Int64 you must supply/will receive 8 byte scalar strings for quads.
For ``in'' params in Win32::API and Win32::API::More and ``out'' in
Win32::API::Callback only, if the argument is a reference, it will automatically
be treated as a Math::Int64 object without having to previously call this
function.
If using Win32::GetLastError
and $^E
does not reveal the problem with your
use of Win32::API, you may turn on Win32::API's very verbose debugging mode as
follows
BEGIN { $Win32::API::DEBUG = 1; } use Win32::API; $function = Win32::API::More->new( 'mydll', 'int sum_integers(int a, int b)' );
Call()
was done on the object.
$!
for new
/Import
failure is broken and deprecatednew
and Import
not setting
$! in the perlvar manpage or Win32 and C error codes overlapping and Win32 error codes being
stringified as different C error codes, checking $!
is deprecated and the
existing, partial setting of $!
, maybe removed in the future. Only check
Win32::GetLastError()
or $^E
to find out why the call failed.
See the Changes
file for more details, many of which not mentioned here.
the Win32::API::Struct manpage
the Win32::API::Callback manpage
the Win32::API::Callback::IATPatch manpage
http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/function-calling-conventions.html
Aldo Calpini ( dada@perl.it ).
Cosimo Streppone ( cosimo@cpan.org )
Daniel Dragan ( bulkdd@cpan.org )
To finally clarify this, Win32::API
is OSI-approved free software;
you can redistribute it and/or modify it under the same terms as Perl
itself.
See http://dev.perl.org/licenses/artistic.html
All the credits go to Andrea Frosini for the neat assembler trick that makes this thing work. I've also used some work by Dave Roth for the prototyping stuff. A big thank you also to Gurusamy Sarathy for his invaluable help in XS development, and to all the Perl community for being what it is.
Cosimo also wants to personally thank everyone that contributed to Win32::API with complaints, emails, patches, RT bug reports and so on.
Win32::API - Perl Win32 API Import Facility |