C# + COM, modify array in parameter
I have a COM object in C# and a Silverlight application(escalated privileges) which is a client to this COM object.
COM object:
[ComVisible(true)]
public interface IProxy
{
void Test(int[] integers);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Proxy : IProxy
{
[ComVisible(true)]
public void Test(int[] intege开发者_开发知识库rs)
{
integers[0] = 999;
}
}
Silverlight client:
dynamic proxy = AutomationFactory.CreateObject("NevermindComProxy.Proxy");
int[] integers = new int[5];
proxy.Test(integers);
I excpect the integers[0] == 999, but the array is intact.
How to make the COM object modify the array?
UPD Works for non-silverlight apps. Fails for Silverlight. How to fix for silverlight?
The short answer is you need to pass the array by ref (see the note in AutomationFactory just above the example [arrays are passed by value in C#]) - The problem then is, SL will barf with an argument exception when you call proxy.Test(ref integers)
(I don't why). The work around is that SL will pass an array by ref if the method takes an object by ref, so this works...
[ComVisible(true)]
public interface IProxy
{
void Test( ref object integers);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Proxy : IProxy
{
[ComVisible(true)]
public void Test(ref object intObj)
{
var integers = (int[])intObj;
integers[0] = 999;
}
}
And with the SL code adding ref like:
dynamic proxy = AutomationFactory.CreateObject("NevermindComProxy.Proxy");
var integers = new int[5];
proxy.Test( ref integers);
Drop the ref from either the caller or the interface definition and it won't update the array.
精彩评论