Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string arrays from COM to C#

I need to access C# methods in a COM dll via COM-like interface. One of the method requires an array of strings to be passed as input.

Am creating a SAFEARRAY and passing it to the COM Interop. However, this does not seem to be working, as I see an exception in the interop layer. (System.Runtime.InteropServices.SafeArrayTypeMismatchException).

Obviously, there seems to be a difference in type being expected.

Pasting the code here:

C# method to be invoked:

public long DoIt3(int nFiles, string[] fileNames);

C++ code invoking the same:

int _tmain()
{
TCHAR *fileNames[128] = { TEXT("C:\\Program Files\\IBM\\RTC.NET"),
                          TEXT("C:\\KIRAN\\Work\\RFT"), TEXT(".\\bin\\Debug") };

SAFEARRAY *pSA = CreateSafeStringArray(3, fileNames);

_tprintf(TEXT("%d"), pIManaged->DoIt3(3, pSA));

SafeArrayDestroy(pSA);
}

static SAFEARRAY *CreateSafeStringArray(long nElements, TCHAR *elements[])
{
SAFEARRAYBOUND saBound[1];

saBound[0].cElements = nElements;
saBound[0].lLbound = 0;

SAFEARRAY *pSA = SafeArrayCreate(VT_VARIANT, 1, saBound);

if (pSA == NULL)
{
    return NULL;
}

for (int ix = 0; ix < nElements; ix++)
{
    VARIANT v;

    VariantInit(&v);

    v.vt = VT_BSTR;
    v.bstrVal = elements[ix];

    long rgIndicies[1];

    rgIndicies[0] = ix + saBound[0].lLbound;

    HRESULT hr = SafeArrayPutElement(pSA, rgIndicies, &v);

    _tprintf(TEXT("%d"), hr);

    VariantClear(&v);
}

return pSA;
}

Any ideas/suggestions are welcome.

like image 865
Kiran M N Avatar asked Mar 28 '26 23:03

Kiran M N


1 Answers

I figured it out! The following code works:

static SAFEARRAY *CreateSafeStringArray(long nElements, TCHAR *elements[])
{
SAFEARRAYBOUND saBound[1];

saBound[0].cElements = nElements;
saBound[0].lLbound = 0;

SAFEARRAY *pSA = SafeArrayCreate(VT_BSTR, 1, saBound);

if (pSA == NULL)
{
    return NULL;
}

for (int ix = 0; ix < nElements; ix++)
{
    BSTR pData = SysAllocString(elements[ix]);

    long rgIndicies[1];

    rgIndicies[0] = saBound[0].lLbound + ix;

    HRESULT hr = SafeArrayPutElement(pSA, rgIndicies, pData);

    _tprintf(TEXT("%d"), hr);
}

return pSA;
}

Thanks for all your suggestions!

like image 82
Kiran M N Avatar answered Apr 02 '26 12:04

Kiran M N