0

I'm working on a managed C++ application that utilizes a C# library to populate a field in an ADO Recordset:

recordset->Fields->GetItem(L"Id")->Value = _variant_t(Library::IdGenerator->GenerateNewId());

However, I'm encountering an error converting the .NET string returned by the library to a _variant_t before adding it to the recordset.

Here is the error I'm getting:

error C2440: '<function-style-cast>' : cannot convert from 'System::String ^' to '_variant_t'

Am I missing a conversion or cast to get this to work?

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
miguelarcilla
  • 1,426
  • 1
  • 20
  • 38

1 Answers1

1

Yes, conversion is required. The _variant_t class is not a very happy match, for an unfathomable reason it is missing a constructor that take a BSTR, the one that takes a _bstr_t is unattractive because it copies the string. Fall back to the native VARIANT type, like this:

using namespace System::Runtime::InteropServices;
...
    String^ s = Library::IdGenerator->GenerateNewId();
    VARIANT v = { VT_BSTR };
    v.bstrVal = (BSTR)Marshal::StringToBSTR(s).ToPointer();
    recordset->Fields->GetItem(L"Id")->Value = v;
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536