EDIT: I've found an answer (with help from Tejs); see below.
I'm developing a Metro app using HTML/Javascript, along with some C#-based helper libraries. Generally speaking I'm having a lot of success calling C# methods from Javascript, but I can't seem to get passing arrays (in my specific case, arrays of strings) to work. Passing individual strings works without issue.
My code is something like this:
// in javascript project
var string1 = ...;
var string2 = ...;
var string3 = ...;
var result = MyLibrary.MyNamespace.MyClass.foo([string1, string2, string3]);
Then, in C#:
// in C# project
public sealed class MyClass {
public static string Foo(string[] strings) {
// do stuff...
}
}
The problem is that the method "Foo" gets an array with the correct length (so in the above example, 3), but all of the elements are empty. I also tried this:
public static string Foo(object[] strings) {
...
That didn't work either - again, the array was the correct size, but all the elements were null.
I've tried passing string literals, string variables, using "new Array(...)" in javascript, changing the signature of "Foo" to "params string[]" and "params object[]", all to no avail.
Since passing individual strings works fine, I can probably work around this with some hackery...but it really seems like this should work. It seems really odd to me that the array is passed in as the right size (i.e. whatever's doing the marshaling knows SOMETHING about the javascript array structure) and yet the contents aren't getting populated.
The solution to your problem is very simple, just it takes a keen eye to notice it. First you must take in the fact that in C# (and quite possibly javascript, as well) that you cannot have an array of arrays (at least not like how you are doing it!) So in your javascript:
var result = MyLibrary.MyNamespace.MyClass.foo([string1, string2, string3]);
and in your C#:
public static string Foo(string[] strings) {
you are going to need to let the method Foo pass several arguments of string arrays, like so:
public static string Foo(string[] string1, string[] string2, string[] string3) {
But if you want to create an array of arrays, you are going to have to use a List constructor:
public static string Foo(List< string[] > strings) {
But the problem with the above answer is that Javascript has not List constructor, so i'd suggest going with the first solution, unless you can find a way to fix this one!
The trick is to use IEnumerable instead of string[]. So replace my original code with the following:
public sealed class MyClass {
public static string Foo(IEnumerable<string> strings) {
// do stuff...
}
}
Also note that IEnumerable works too, if you need to pass arrays of something other than strings.
Thanks @Tejs for the inspiration!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With