【问题标题】:Setting an array using Ruby and Win32OLE使用 Ruby 和 Win32OLE 设置数组
【发布时间】:2014-12-04 15:49:41
【问题描述】:

我正在尝试使用 Ruby v1.93 在 COM 对象中设置数组属性。将 COM 中的数组编组到 Ruby 数组中是可行的,但反之则不行。如何将 Ruby 数组编组到 COM 中?

该属性包含在 .NET 程序集中:

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

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

我的整个 ruby​​ 脚本是:

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

输出是:

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


    【解决方案1】:

    试试这个:

    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
    

    确保在 ruby​​-doc.org 上查找 #_setproperty 方法,了解为什么您的数组包含在数组中以及为什么变量常量在数组中。

    【讨论】:

    • 嗯...您的新代码前面是我已经在尝试的代码行:com_class.MyArray = [20,30],它会生成我在帖子中显示的错误。假设您打算省略该行,我尝试在没有它的情况下运行,但对 setproperty 的调用失败并显示:in 'ole_method': not found MyArray.
    • 其实 print com_class.ole_get_methods 给了我[]。
    • 糟糕,要删除失败的行。糟糕的复制/粘贴工作。您是否尝试过运行此(已编辑)代码?结果和/或错误是什么?
    • 感谢您的跟进。我确实尝试了编辑后的代码甚至是相关的实验,但得到了不同的错误(请参阅我之前的两个 cmets)。
    • 啊,我第一次看不懂你的回答。现在我懂了。我对 COM 对象的内部工作了解不多,但 Ruby 的 WIN32OLE 支持无法发现您的属性似乎很奇怪。如果运行“com_class.ole_get_methods”返回一个空数组,那么这似乎是一个显示停止器。我没有主意了。
    【解决方案2】:

    有点晚了,但我在尝试设置System.Security.Cryptography.TripleDESCryptoServiceProvider 的密钥时遇到了同样的问题,因为我在没有OpenSSL 的情况下将一些加密算法实现到 ruby​​ 引擎中

    这不起作用:

    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]
    

    这确实有效:

    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
    

    【讨论】:

      猜你喜欢
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 2011-10-08
      • 2011-01-22
      • 1970-01-01
      相关资源
      最近更新 更多