NAME

Win32::API - Perl Win32 API Import Facility

SYNOPSIS

 #### Method 1: with prototype

 use Win32::API;
 $function = Win32::API::More->new(
     'mydll', 'int sum_integers(int a, int b)'
 );
 $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)'
 );
 $return = $function->Call(3, 2);

 #### Method 3: with parameter list 
 
 use Win32::API;
 $function = Win32::API::More->new(
     'mydll', 'sum_integers', 'II', 'I'
 );
 $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'
 );
 $return = $function->Call(3, 2);
 
 #### Method 5: with Import (slightly faster than ->Call)

 use Win32::API;
 Win32::API::More->Import(
     'mydll', 'int sum_integers(int a, int b)'
 );  
 $return = sum_integers(3, 2);

ABSTRACT

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.

DESCRIPTION

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.

IMPORTING A FUNCTION

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.

IMPORTING A FUNCTION BY PROTOTYPE

You need to pass 2 or 3 parameters:

  1. The name of the library from which you want to import the function. If the name is undef, you are requesting a object created from a function pointer, and must supply item 2.

  2. This parameter is optional, most people should skip it, skip does not mean supplying undef. Supply a function pointer in the format of number 1234, not string "\x01\x02\x03\x04". Undef will be returned if the pointer is not readable, GetLastError will be ERROR_NOACCESS.

  3. 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 retrive 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 Win32::API::Type for a list of the known parameter types and Win32::API::Struct 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.

IMPORTING A FUNCTION WITH A PARAMETER LIST

You need to pass at minimum 4 parameters.

1. The name of the library from which you want to import the function.
2. This parameter is optional, most people should skip it, skip does not mean supplying undef. Supply a function pointer in the format of number 1234, not string "\x01\x02\x03\x04". Undef will be returned if the pointer is not readable, GetLastError will be ERROR_NOACCESS.
3. The name of the function (as exported by the library) or for function pointers a name that is "friendly" to you. This name for a function pointer is also used for Import(). No attempt is made to retrive such a name from any DLL's export table in the 2nd case.
4. The number and types of the arguments the function expects as input.
5. The type of the value returned by the function.
6. And optionally you can specify the calling convention, this defaults to '__stdcall', alternatively you can specify '_cdecl' or '__cdecl' (API > v0.68) or (API > v0.70_02) 'WINAPI', 'NTAPI', 'CALLBACK' (__stdcall), 'WINAPIV' (__cdecl) . False is __stdcall. Vararg functions are always cdecl. MS DLLs are typically stdcall. Non-MS DLLs are typically cdecl. If API > v0.75, mixing up the calling convention on 32 bits is detected and Perl will 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.

1.

The first parameter is the name of the library file that exports this function; our function resides in the KERNEL32.DLL system file.

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:

1. The directory from which the application loaded.
2. The current directory.
3. The Windows system directory (eg. c:\windows\system or system32).
4. The Windows directory (eg. c:\windows).
5. The directories that are listed in the PATH environment variable.

So, you don't have to write C:\windows\system\kernel32.dll; only kernel32 is enough:

$GetTempPath = new Win32::API::More('kernel32', ...
2.

Since this function is from a DLL, skip the 2nd parameter. Skip does not mean supplying undef.

3.

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 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. 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.

4.

The third parameter, the input parameter list, specifies how many arguments the function wants, and their types. It can be passed as a single string, in which each character represents one parameter, or as a list reference. The following forms are valid:

"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 perlfunc 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 Math::Int64 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.

It is suggested to not use P as a return type and instead use N and read the memory yourself, and free the pointer if applicable. This pointer is effectivly undefined after the C function returns control to Perl. The C function may not hold onto it after the C function returns control. There are exceptions where the pointer will remain valid after the C function returns control, but tread at your own risk, and at your knowledge of Perl interpretor's C internals.

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 more
K: value is a Win32::API::Callback object, in parameter only, (see Win32::API::Callback)
V: no value, no parameters, stands for void, may not be combined with any other letters, equivelent 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 explictly says the parameters must be big endian. If there is no documentation for your C function or no mention of endianess in the doucmentation, this doesn't apply to you and skip the rest of this paragraph. There is no inherant support for big endian parameters. Perl's scalar numbers model is that numeric scalars are effectivly opaque and their machine representation is irrelavent. 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 that the C function is getting big endian 5. See perlpacktut for more.

Our function needs two parameters: a number (DWORD) and a pointer to a string (LPSTR):

$GetTempPath = new Win32::API('kernel32', 'GetTempPath', 'NP', ...
4.

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, otherwise either the function or the library could not be loaded; in this case, $! will be set to the error message reported by Windows. 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: $!\n";
}

CALLING AN IMPORTED FUNCTION

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.*$//;

USING STRUCTURES

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 herustics are done to vaildate 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 Win32::API::Type) 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 Win32::API::Struct.

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:

  1. you have to pack() the required elements in a variable:

    $lpPoint = pack('ll', 0, 0); # store two LONGs
  2. to 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...

EXPORTED FUNCTIONS

ReadMemory

$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

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

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.

IsBadReadPtr

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 giberrish. 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 alot more on this function of the same name.

SafeReadWideCString

$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.

CONSTRUCTORS

new

$obj = Win32::API::More->new([$dllname | (undef , $funcptr)], [$c_proto | ($in, $out [, $calling_convention])]);

See "DESCRIPTION".

Import $obj = Win32::API::More->Import([$dllname | (undef , $funcptr)], [$c_proto | ($in, $out [, $calling_convention])]);

See "DESCRIPTION".

METHODS

Call

The main method of a Win32::API object. Documented elsewhere in this document.

UseMI64

$bool = $APIObj->UseMI64();
$oldbool = $APIObj->UseMI64($newbool);

Turns on Quads as Math::Int64 objects support for a particular object instance. You must call "use" in perlfunc/"require" in perlfunc 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 your 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.

HISTORY

UseMI64 API change

Starting in 0.71, UseMI64 on a set returns old value, not previously new value.

fork safe

Starting in 0.71, a Win32::API object can go through a fork and work correctly in the child and parent psuedo-processes. Previously when either psuedo-processes exited, the DLL would be unloaded and the other psuedo-processes would crash if a Call() was done on the object.

return value signedness

Prior to 0.69, for numeric integer types, the return scalar was always signed. Unsigned-ness was ignored.

shorts

Prior to 0.69, shorts were not supported. 'S' meant a sturct. To fix this Win32::API::More class was created for 0.69. 'S'/'s' now means short, per pack's letters. Struct has been moved to letter 'T'. Win32::API will continue to exist for legacy code.

float return types

Prior to 0.69, if a function had a return type of float, it was silently not called.

buffer overflow protection

Introduced in 0.69. If disabling is required, which is highly not recommended, set an enviromental variable called WIN32_API_SORRY_I_WAS_AN_IDIOT to 1.

automatic un/pack

Starting with 0.69, when using Win32::API::More, there is automatic un/packing of pointers to numbers-ish things for in parameters when using the C prototype interface.

Quads on 32 bit

Added in 0.70.

__stdcall vs __cdecl checking on 32 bits

Added in 0.76_01

Import returns an api obj on success, undef on failure, instead of 1 or 0

Added in 0.76_02

See the Changes file for more details, many of which not mentioned here.

BUGS AND LIMITATIONS

  Unicode DLL paths

Untested.

  ithreads

Minimally tested.

  C functions getting utf8 scalars vs byte scalars

Untested and undefined.

SEE ALSO

Math::Int64

Win32::API::Struct

Win32::API::Type

Win32::API::Callback

Win32::API::Callback::IATPatch

http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/function-calling-conventions.html

AUTHOR

Aldo Calpini ( dada@perl.it ).

MAINTAINER

Cosimo Streppone ( cosimo@cpan.org )

MAJOR CONTRIBUTOR

Daniel Dragan ( bulkdd@cpan.org )

LICENSE

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

CREDITS

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 unvaluable 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.