Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an array from JS to C# with COM-Interop

I'm returning some data from my JavaScript code to my C# code via COM Interop and the WebBrowser WPF control. I have successfully returned the data which looks like this in Javascript:

var result = new Array(); 
result[0] = cbCamera.selectedItem; 
result[1] = cbMicrophone.selectedItem;

Now I have the object result in C# which looks like this:

result.GetType(); 
{Name = "__ComObject" FullName = "System.__ComObject"}

How can I get the javascript strings contained in this array which is in this ComObject?

like image 895
vanja. Avatar asked Oct 15 '22 16:10

vanja.


1 Answers

To find the underlaying type of the object contained in the rutime callable wrapper (System.__ComObject) you would use refection. You would then be able to create or cast to a managed type from this information.

For example;

string type = (string)result.GetType().InvokeMember("getType",
BindingFlags.InvokeMethod, null, result, null);

Alternatively you could use invokeMember to retrieve the values. For example you could invoke the valueOf method to convert the array to the most meaningful primitive values possible or toString to covert the array to a csv string.

string result = (string)result.GetType().InvokeMember("toString",
BindingFlags.InvokeMethod, null, result, null);
string[] jsArray = result.Split(',');
// c# jsArray[n] = js result[n] 

EDIT: A third way to do this in c# 4.0 is to use the new dynamic type. The dynamic type makes it really easy to make late-bound calls on COM objects.

string csv = ((dynamic)result).toString();
like image 57
Fraser Avatar answered Oct 18 '22 12:10

Fraser