C++ – Pass an element from C type string array to a COM object as BSTR? (in C++)

bstrccom

I am writing a C++ DLL that is called by an external program.

1.) I take an array of strings (as char *var) as an argument from this program.

2.) I want to iterate through this array and call a COM function on each element of the string array. The COM function must take a BSTR:

DLL_EXPORT(void) runUnitModel(char *rateMaterialTypeNames) {

    HRESULT hr = CoInitialize(NULL);

    // Create the interface pointer.
    IUnitModelPtr pIUnit(__uuidof(BlastFurnaceUnitModel));

    pIUnit->initialiseUnitModel();

    int i;
    for(i=0; i < sizeOfPortRatesArray; i++)
            pIUnit->createPort(SysAllocString(BSTR((const char *)rateMaterialTypeNames[i])));

I think its the SysAllocString(BSTR((const char *)rateMaterialTypeNames[i])) bit that is giving me problems. I get an access violation when the programs runs.

Is this the right way to access the value of the rateMaterialTypeName at i? Note I am expecting something like "IronOre" as the value at i, not a single character.

Best Answer

If you're using Microsofts ATL, you can use the CComBSTR class. It will accept a char* and create a BSTR from it, also, you don't need to worry about deleting the BSTR, all that happens in the dtor for CComBSTR.

Also, see Matthew Xaviers answer, it doesn't look like you're passing your array of strings into that function properly.

Hope this helps

Related Topic