In the past, when I used the webbrowser written by VC to interact with JS, When I encountered the need to pass arrays, I always used safearray, that is, vbarray.
Although I know that JS Arrays can be directly created through interfaces, we all know that VC implementation is still very troublesome and trivial, so we have been using safearray.
Now when I use C # To write data, I have encountered a problem.
A function in one of my iexternal interfaces cannot pass safearray.
The code at the beginning is as follows:
[Return: financialas (unmanagedtype. safearray, safearraysubtype = varenum. vt_bstr)]
Public String [] getfilesname (string strdir)
{
Return directory. getfiles (strdir );
}
It seems that there is no problem.
However, the Type Mismatch Error is displayed when the JS script is running.
Then I changed the parameter safearraysubtype many times. It is always Type mismatch.
No one in China seems to be able to raise or solve this problem.
There is a foreign, you can look at: http://www.eggheadcafe.com/forumarchives/NETFrameworkinterop/Dec2005/post25276812.asp
It solves the problem.
Solution:
How to return safearray (vbarray)
In fact, if you directly return an object [], because you have set comvisble (true), C # automatically sets the returned value of object [] to safearray.
So you can directly write:
Public object [] getfilesname (string strdir)
{
Return new object [] {"string1", "string2 "};
}
JS will recognize it as vbarray.
You can also set the standard:
[Return: financialas (unmanagedtype. safearray, safearraysubtype = varenum. vt_variant)]
Public object [] getfilesname (string strdir)
{
Return new object [] {"string1", "string2 "};
} P.s: the actual implementation is as follows: Use convertall to convert string [] to object [] [Return: marshalas (unmanagedtype. safearray, safearraysubtype = varenum. vt_variant)] public object [] getfilesname (string strdir) {var arrtest = directory. getfiles (strdir); object [] arrob = array. convertall (arrtest, new converter <string, Object> (string2object); Return arrob;} private object string2object (string Str) {return (object) STR ;}
How to return JS array:You must first Add a reference to Microsoft. JScript in C # And then do the following:
Public object getfilesname (string strdir)
{
VaR arrtest = directory. getfiles (strdir );
Return Microsoft. JScript. globalobject. array. constructarray (arrtest );
} Note that the function returns an object instead of object []. in this way, JS calls this function to directly return jsarray. instead of converting from vbarray to jsarray. the Chinese in this aspect on the Internet seems incomplete. I hope I can help you with it. if you can tell me, it will be very gratifying. Thank you!