-1

I need to manipulate the StrVal as the struct is marshalled to managed C#. I am trying to use BSTR string type, as it saves the memory allocation actions but I am not familiar with unmanaged data types. The problem is that I do not see any changes made to the value.

typedef struct {
    int Id;
    BSTR StrVal;
}packet;

packet pks [5];

// ...

 pks[i].StrVal = L"abcdefghij";

 for (int i = 0; i < 10; i++)
 {
    pks[i]=i;

    //pks[i].StrVal = SysAllocString(L"abcdefghi"+i);
    pks[i].StrVal[9]=i+'0';
 }

How can I accomplish the task?

Niall
  • 30,036
  • 10
  • 99
  • 142
Avia Afer
  • 866
  • 2
  • 8
  • 29

2 Answers2

2

Change the init to

pks[i].StrVal = SysAllocString(L"abcdefghij");
LPs
  • 16,045
  • 8
  • 30
  • 61
1

The problem is that pks[i].StrVal = L"abcdefghij" just points the BSTR to a string literal, it doesn't copy the value in the BSTR, in addition to the fact that the BSTR whilst typedefed to whar_t* does not behave like a C string. To work with the BSTR you must limit yourself to the Sys... family of functions (e.g. SysAllocString) or if the ATL is available, use that. To initialise and allocate the string;

pks[i].StrVal = SysAllocString(L"abcdefghij");

Looking at the for loop alone (i.e. not allocating as above), the concatenation could be easily done with ATL::CComBSTR;

CComBSTR temp(L"abcdefghi");
temp += std::to_wstring(i).c_str();
pks[i].StrVal = temp.Detach();

VarBstrCat provides another alternate for the concatenation.

Niall
  • 30,036
  • 10
  • 99
  • 142
  • thanks for your good sample code, i have no knowlage of all types you mentioned, and while reviewing the alternative, it's nice that `CComBSTR` let use without allocating. though which approach is less expensive, as i might marshall to managed code, by the M's of them – Avia Afer Oct 19 '15 at 20:35