从.Net到vb6编组System.Array [英] Marshalling System.Array from .Net to vb6

查看:52
本文介绍了从.Net到vb6编组System.Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.Net组件,该组件具有一个COM可见类,该类具有返回System.Array的方法.在后台,它返回一个字符串数组,但是返回类型声明为System.Array.不要问我为什么",我知道我可以将返回类型声明为string [],这样就可以了,但是我的问题特别是当它返回System.Array时.因此,为简单起见,.Net方法如下:

I have a .Net component that has a COM visible class with a method that returns a System.Array. Under the hood it returns a string array, however the return type is declared as System.Array. Don't ask me "why", I know I can declare the return type as string[] and it will be fine, but my question is for particularly when it returns System.Array. So for simplicity the .Net method is the following:

public Array GetData()
{
    return new string[] { };
}

然后在VB6项目中,无论我如何尝试,都无法以字符串形式访问和遍历数组元素.下面是我的VB6代码段,该代码段不起作用:

Then in the VB6 project no matter how I try I cannot access and traverse through the array elements as strings. Below is my VB6 code snippet that doesn't work:

Dim objRetVal As Object
Dim resData As Variant
Dim strData As String

Set objRetVal = NetClassInstance.GetData()

For Each resData In objRetVal
    strData = CStr(resData)
    MsgBox "strData = " & strData
Next

上面的NetClassInstance是我的.Net组件中COM Visible .Net类的实例.因此,它始终失败,无法将System.Array编组为VB6的字符串数组,而我可以循环访问该数组中的字符串.请注意,objRetVal不是Nothing并且不为空,它具有数据,只是resData不会读取数组中的字符串值.

The NetClassInstance above is an instance of the COM Visible .Net class in my .Net component. So, it fails all the time, no way it can marshal System.Array to string array for VB6 that I can loop and access strings in the array. Note, that the objRetVal is not Nothing and is not empty it has the data, just resData doesn't read a string value in the array.

我知道如果我从.Net方法返回字符串数组,那么它最有可能在VB6端工作,但是我想知道是否存在一种方法来进行适当的封送处理并将返回的System.Array转换为string()在VB6一侧的数组.

I know if I return string array from my .Net method then it will most probably work at the VB6 end, but I want to know if there is a way to do proper marshaling and convert the returned System.Array into string() array on VB6 side.

推荐答案

我要做的就是遵循汉斯(Hans)和xxbbcc的注释,这使我得以暗示运行代码所需的条件.所以,我用以下return装饰了我的方法:MarshalAs标签,它对我来说很好用:

All I needed to do is to follow Hans's and xxbbcc's comments which brought me to the hint what was required to make the code run. So, I adorned my method with the following return:MarshalAs tag and it worked well for me:

[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
public Array GetData()
{
    return new string[] { };
}

谢谢大家的支持.

这篇关于从.Net到vb6编组System.Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆