Can on marshal a string[] to a safearray variant?

北城以北 提交于 2019-12-11 02:39:41

问题


When I marshal my function returning a string[] as UnmanagedType.Struct with SafeArraySubType = VarEnum.VT_ARRAY as in

namespace StackOverflow
{
  [ComVisible(true)]
  [Guid("4BDC43D4-8FD7-4F58-BEE5-E57C3C144C1B")]
  public class Array
  {
    [return: MarshalAs(UnmanagedType.Struct, SafeArraySubType = VarEnum.VT_ARRAY)]
    public string[] StringArray()
    {
      return new string[] { "foo", "bar" };
    }
  }
}

I was expecting to get a variant (UnmanagedType Enumeration)

Struct
A VARIANT, which is used to marshal managed formatted classes and value types.

However the VBScript code

WScript.Echo TypeName(CreateObject("StackOverflow.Array").StringArray)

reports String() (which is not a Variant() and therefore I will get type missmatch errors later when accesing the array).

When I change my code to either

public object[] ObjectArray()
{
  return new object[] { "foo", "bar" };
}

public object PlainObject()
{
  return new object[] { "foo", "bar" };
}

the VBScript code seems to works fine, however I would like to know why I cannot return a string[] and manually marshall it to a variant containing a safearray of variants.

It seems that the SafeArraySubType has no effect. What is my mistake?


回答1:


Thats because the SafeArraySubType only applies to SafeArrays.

MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)]


来源:https://stackoverflow.com/questions/31433552/can-on-marshal-a-string-to-a-safearray-variant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!