Calling a C# .dll from Ruby via COM

2019-07-19 17:56发布

问题:

I'm trying to call a few methods from C# in my Ruby code. First, I am creating a .dll in Visual Studio 2008. I'm registering for COM interop when I build.

To test out this new process, I created a simple little DivideTwo method in C#-

        public double DivideTwo(double a, double b)
    {
        return a / b;
    }

In Ruby, I do the following:

require 'win32ole'
test=WIN32OLE.new('DllAttempt.CsharpDll')
x=test.DivideTwo(5,5)
puts x
#x=1

I get all excited because I think I've gotten it to work! I decide to return a hash from C# next via the following method:

        public Hashtable Hashtbl(string a,int b)
    {
        Hashtable bbDataHash = new Hashtable();
        bbDataHash.Add(a, b);
        return (Hashtable)bbDataHash;
    }

In Ruby, I do the following:

require 'win32ole'
test=WIN32OLE.new('DllAttempt.CsharpDll')
x=test.Hashtbl("key",1)
puts x
#x=#<WIN32OLE:0x283f3f4>

As you can see, I get back a COM object. I can't get anything out of the object. x.each {block} gives me a "failed to get IEnum Interface" error. Interestingly, if I return an array fro C#, .each works on that object.

Am I even going about this the right way?

Thanks

回答1:

While HashTable is ComVisible, it's not going to get magically converted from a C# collection into a Ruby collection through COM marshaling.

I don't know any Ruby, so I can't give you an example, but you're probably going to need to call HashTable.GetEnumerator and use the IEnumVARIANT returned from that to traverse your HashTable in Ruby.



回答2:

try reading http://msdn.microsoft.com/en-us/library/ee817653.aspx

you'll have to follow the links to find the page which gives you managed-to-COM data type conversion