Setting an array using Ruby and Win32OLE

1

I'm trying to set an array property in a COM object using Ruby v1.93. Marshalling an array from COM into a Ruby array just works, but not in the other direction. How do I marshall a Ruby array into COM?

The property is contained in a .NET assembly:

namespace LibForRuby
{
   public class MyClass
   {
      public MyClass()
      {
         MyInt = 1;
         MyArray = new[] {2, 3};
      }

      public int MyInt { get; set; }
      public int[] MyArray { get; set; }
   }
}

My entire ruby script is:

require 'win32ole'

com_class = WIN32OLE.new('LibForRuby.MyClass')

puts 'Before:'
my_int = com_class.MyInt
puts my_int
my_array = com_class.MyArray
print my_array
puts

puts 'After:'
com_class.MyInt = 10
my_int = com_class.MyInt
puts my_int
com_class.MyArray = [20,30]
my_array = com_class.MyArray
print my_array

The output is:

C:\Ruby193\bin>test
Before:
1
[2, 3]
After:
10
C:/Ruby193/bin/test.rb:13:in `method_missing': (in setting property `MyArray': )
 (WIN32OLERuntimeError)
    OLE error code:0 in <Unknown>
      <No Description>
    HRESULT error code:0x80020005
      Type mismatch.
        from C:/Ruby193/bin/test.rb:13:in `<main>'
ruby
win32ole
asked on Stack Overflow Dec 4, 2014 by Jim C • edited Dec 4, 2014 by Jim C

2 Answers

0

Try this:

puts 'After:'
com_class.MyInt = 10
my_int = com_class.MyInt
puts my_int
com_class._setproperty(
com_class.ole_method_help('MyArray').dispid,
[[20,30]], 
[WIN32OLE::VARIANT::VT_ARRAY]
)
my_array = com_class.MyArray
print my_array

Make sure to lookup the #_setproperty method at ruby-doc.org to see why your array is enclosed in an array and why the variant constant is inside an array.

answered on Stack Overflow Dec 5, 2014 by Chuck Remes • edited Dec 6, 2014 by Chuck Remes
0

A bit late, but I just had the same problem while trying to set the key of System.Security.Cryptography.TripleDESCryptoServiceProvider as I am implementing some encryption algorithm into a ruby engine without OpenSSL

This does not work:

crypto = WIN32OLE.new("System.Security.Cryptography.TripleDESCryptoServiceProvider")
crypto.key = [62,116,108,70,56,97,100,107,61,51,53,75,123,100,115,97]

This does work:

arr = [1,2,3,4]
crypto = WIN32OLE.new("System.Security.Cryptography.TripleDESCryptoServiceProvider")
vArr = WIN32OLE_VARIANT.array([arr.length],WIN32OLE::VARIANT::VT_UI1)
arr.each_with_index {|val,index| vArr[index]=val}
crypto.key = vArr
answered on Stack Overflow Jan 27, 2018 by Sancarn • edited Jan 28, 2018 by Sancarn

User contributions licensed under CC BY-SA 3.0