Passing Strings to COM/ActiveX in C++ Builder

In C++ Builder, when passing a string to an ActiveX (COM) function, a BSTR is required. This is different than a NULL-terminated WideString.

The correct syntax looks like this:

long lSuccess;
BSTR bstr = SysAllocString(L"UnlockCode");
spChilkatMHT->UnlockComponent (bstr, &lSuccess);
SysFreeString( bstr );

The following is incorrect because a NULL-terminated WideString is passed, and not a BSTR:

// This code will probably cause the program to crash...
long lSuccess;
spChilkatMHT->UnlockComponent (L"UnlockCode", &lSuccess);

CodeGear C++ Builder: Passing Strings to COM / ActiveX Methods

The correct way to pass a string to a COM/ActiveX method is to use “WideString (theString).c_bstr()” because ActiveX controls/components require BSTR’s, and not strings.  BSTR’s are wide strings (Unicode) where the length of the string precedes the string in memory.

The C++ Builder code to pass a string to an ActiveX function is as follows:

  FClientSock = new TChilkatSocket(Owner);
  success = FClientSock->UnlockComponent(WideString("30 day trial").c_bstr());