Marshalling System.Array from .Net to vb6

守給你的承諾、 提交于 2019-12-10 22:39:59

问题


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[] { };
}

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

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.

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.


回答1:


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[] { };
}

Thank you all for supportive comments.




回答2:


Unless I missed something it seems that you have not set any value to "resdata" hence the empty returned string.

For Each resData In objRetVal ''Nothing to tie resdata to...
  strData = CStr(resData) ''resdata is already empty, returning nothing here...
  MsgBox "strData = " & strData
Next

Seeing that you are using an object "resdata" should be something like -

resData = objRetVal.StringReturned  ''Whatever the return name might be...  

For Each resData In objRetVal ''Now has a value...
  strData = CStr(resData) ''Returning your query...
  MsgBox "strData = " & strData
Next


来源:https://stackoverflow.com/questions/39351476/marshalling-system-array-from-net-to-vb6

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