سؤال

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?

هل كانت مفيدة؟

المحلول

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;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top