Pergunta

I am working with a third-party COM component (i.e. do not have its code). The method in question has the following outline:

HRESULT GetTableInfo(  
[in] BSTR bstrTableName, 
[in,out] SAFEARRAY(BSTR) bstrColumnTitles, 
[in,out] SAFEARRAY(long) lColumnPos );

I have tried to pass a ref to a fixed-size array ((Array)string[6]) and to a List.ToArray(), but it keeps crashing on me. E.g.

Array arr1 = (Array) new string[500];
Array arr2 = (Array) new int[500];
table.GetTableInfo(filename, ref arr1, ref arr2);

To be more specific: I already tried any value for the size (the correct one should be 44). Tried the same for the capacity of a List<>, but that didn't help either. I also tried different types, but it does not accept any other than int.

I don't know why it keeps crashing on me with a general error of that COM component (basically indicating that something is wrong, yet not saying what exactly), since I can confirm that the following VB code works:

Dim TitleList() As String
Dim PositionList() As Long 
Call objTable.GetTableInfo(txTableFile.Text, TitleList, PositionList)

Does anyone have a clue on why this happens? Or alternatively, can anyone provide me a port of that VB code to C#? I have tried to google for tutorials, but all they say is "only fixed size arrays are allowed". I wonder how that code works then, as no size is specified.

Thx i.a.

Foi útil?

Solução

Have you read Default Marshaling for Arrays? As far as I can tell this should "just work" as long as you use the MarshalAs attribute on the PInvoke declaration to indicate that the array should be marshalled as a safe array.

As far as I can tell the correct PInvoke declaration should be something along the lines

public static string extern GetTableInfo(
    string tableName,
    [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VT_BSTR)]
    ref string[] columnTitles,
    [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VT_I8)]
    ref long[] columnPos
);

Can you show us what your PInvoke declaration looks like?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top