开发者

Reading a struct array encapsulated in an Object in c#

开发者 https://www.devze.com 2023-03-08 14:28 出处:网络
I am using reflection to handle an assembly loaded at runtime. My problem is that one of the methods has an output parameter which contains an array of structs.

I am using reflection to handle an assembly loaded at runtime. My problem is that one of the methods has an output parameter which contains an array of structs.

Here are the declarations from assembly:

public struct WHATEVER
{
}

public class SOMECLASS
{
    public static int methodCall(out WHATEVER[] ppWhateverStructs);
}

And here's how I tried to execute:

Type tWHATEVER = Assembly.Load("path-to-Assembly").GetType("WHATEVER");
Type tSOMECLASS = Assembly.Load("path-to-Assembly").GetType("SOMECLASS");

Array objStructs = Array.CreateInstance(tWHATEVER, 1);
object[] Params = new object[] { @objStructs };             // tried with and without "@" - same thing

MethodInfo method = tSOMECLASS.GetMethod("methodCall", new Type[] 开发者_如何学Python{ tWHATEVER.MakeArrayType().MakeByRefType() });
retVal = method.Invoke(null, Params);

when I put 'Params' on watch window it shows me that it contains a 1-element array which also contains an N-sized array filled with elements, and objStructs is unchanged. This is correct. My problem is I don't know how to pick items from sub-array:

object objRestuls = Params[0];

This statement works, shows the items I expect in watch-window, but I don't know how to iterate and pick them up from object. When I try this:

object [] objRestuls = (object [])Params[0];

The following exception is thrown:

An unhandled exception of type 'System.InvalidCastException' occurred in TestAssembly.dll

Additional information: Unable to cast object of type 'TestAssembly.WHATEVER[]' to type 'System.Object[]'.

Does anyone have a hint on how to read an struct-array encapsulated in an object?


You could use:

Array array = (Array) Params[0];

and then iterate over it using the members of Array, or even using foreach (which will box each element).

The reason it's currently not working is that an array of value type values isn't an array of references - so this wouldn't even compile:

// Invalid
object[] array = new int[10];


Did you try TestAssembly.WHATEVER w0 = (TestAssembly.WHATEVER)Params[0][0]?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号