Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically discover a Win32::OLE object's properties and methods in Perl?

Tags:

perl

com

win32ole

With Perl, it's quite easy using the Win32::OLE library to load up COM/OLE objects and control them. The issue I'm running into is knowing exactly what methods and properties are available in the object I'm accessing. Some OLE toolkits in other languages can generate a static interface for you by reading all of the properties and methods that are available on the object. Does such a facility exist with Perl's Win32::OLE library?

like image 327
Robert P Avatar asked Mar 23 '11 00:03

Robert P


3 Answers

You should access the properties from the Win32::OLE object's keys directly. Let's use Excel as the example. The code is from Win32::OLE examples - properties.pl It will show all properties of an Win32::OLE object.

my $Excel = Win32::OLE->new('Excel.Application', 'Quit');
# Add a workbook to get some more property values defined
$Excel->Workbooks->Add;
print "OLE object's properties:\n";
foreach my $Key (sort keys %$Excel) {
    my $Value;

    eval {$Value = $Excel->{$Key} };
    $Value = "***Exception***" if $@;

    $Value = "<undef>" unless defined $Value;

    $Value = '['.Win32::OLE->QueryObjectType($Value).']' 
      if UNIVERSAL::isa($Value,'Win32::OLE');

    $Value = '('.join(',',@$Value).')' if ref $Value eq 'ARRAY';

    printf "%s %s %s\n", $Key, '.' x (40-length($Key)), $Value;
}

In one line, to get all properties of a Win32::OLE object:

keys %$OleObject;

All OLE methods can be retrieved via Win32::OLE::TypeInfo. this block of code will print all the method names of $OleObject:

my $typeinfo = $OleObject->GetTypeInfo();
my $attr = $typeinfo->_GetTypeAttr();
for (my $i = 0; $i< $attr->{cFuncs}; $i++) {
    my $desc = $typeinfo->_GetFuncDesc($i);
    # the call conversion of method was detailed in %$desc
    my $funcname = @{$typeinfo->_GetNames($desc->{memid}, 1)}[0];
    say $funcname;
}
like image 177
Yi Zhao Avatar answered Nov 14 '22 19:11

Yi Zhao


One thing is for sure, if you do this:

print Data::Dumper->Dump( [ $my_ole_object ] )

you'll likely only get an endless loop. But you can modify it like this:

local $Data::Dumper::Maxdepth = 2;
print Data::Dumper->Dump( [ $my_ole_object ] )

And then you can at least see the property names. To see their next level of values, you will need Maxdepth=3. I'm not exactly sure how to look at all the methods other than documentation.

like image 25
Axeman Avatar answered Nov 14 '22 19:11

Axeman


No. but it looks like the necessary type discovery code is already in Win32::OLE's implementation. You can use it as a reference to write your own perl extension that exposes function and method types and names.

like image 1
Sheng Jiang 蒋晟 Avatar answered Nov 14 '22 19:11

Sheng Jiang 蒋晟