Exception trying to convert ON_wString to std::string

Hello,

Working on my plugin running on Rhinoceros (x64) and developed using vc++ on visaul studio 2010 I founded a strange issue.

I need to convert an ON_wString to a std::wstring but it throws an exception.

An example of the code follows:

std::wstring stdString1 = L"";
wchar_t charArray1[256];
memset(charArray1, L'\0', 256);
charArray1[0] = 'a';
ON_wString onString1(charArray1);
stdString1 = onString1.Array(); // It works

std::wstring stdString = L"";
wchar_t charArray[256];
memset(charArray, L'\0', 256);
ON_wString onString(charArray);
stdString = onString.Array(); // Unhandled exception: Access violation reading
                              // location 0x0000000000000000

It seems that a call to the function ON_wString::Array() retruns a NULL pointer if the string is empty.
I expected it returns a valid pointer to an empty char (like std::wstring does).

Is it a bug, a desired behavior or I’m doing something wrong?

Extra question:
During the copy of an ON_wString to a std::wstring (e.g. std::wstring stdString = ON_wString(“foo”)) which is the function that handles the conversion?
I though there was a cast operator from ON_wString to wchar_t* or something similar but I did not find such a function.

Thank you!

Hi @margari,

Does this work for you?


CRhinoCommand::result CCommandTest::RunCommand(const CRhinoCommandContext& context)
{
  ON_wString str = L"Hello Rhino!";

  std::wstring wstr(static_cast<const wchar_t*>(str));

  RhinoApp().Print(L"%s\n", wstr.c_str());

  return CRhinoCommand::success;
}

– Dale

Hi @dale,

Yes it does but the the following code does not…

CRhinoCommand::result CCommandTest::RunCommand(const CRhinoCommandContext& context)
{
  ON_wString str = L"";

  std::wstring wstr(static_cast<const wchar_t*>(str));

  RhinoApp().Print(L"%s\n", wstr.c_str());

  return CRhinoCommand::success;
}

I had a problem only with empty strings. I can manage it by testing the string length but I think ON_wString shold be able to manage empty strings.

Can you clarify my doubts?

Thank you!

I’m confused? How should ON_wString handle empty strings differently?

– Dale

Couldn’t it return a valid pointer to an NULL (L’\0’) character when the function ON_wString::Array() is called?
As std::wstring does so with its function std::wstring::c_str() for example.

Maybe I miss something obvious for you…

ON_wString str = L"";
const wchar_t* charPointer = str.Array(); // This return a NULL pointer

std::wstring str1 = L"";
const wchar_t* charPointer1 = str1.c_str(); // This return a valid pointer to a NULL char

Many thanks!

Hi @margari,

Yes, I see that. We can fix ON_wString::Array in the current version of Rhino. But we’re not going to fix Rhino 5. Thus, your best bet is probably to create a utility function that does the conversion in your preferred manner.

– Dale

Thank you!