开发者

How to compare managed and unmanaged Strings?

开发者 https://www.devze.com 2023-01-08 08:41 出处:网络
I have an application that uses managed System::String in the UI elements, but then refers to un-managed (read: legacy) code for the more complex computation.

I have an application that uses managed System::String in the UI elements, but then refers to un-managed (read: legacy) code for the more complex computation.

Additionally, there is not a consistent encoding for the strings - managed strings can be either regular "strings" or Unicode L"strings" and un-managed strings come in all of char *, wchar_t *, std::string, std::wstring varieties.

What is the best way to compare the various flavors of strings? I'm hoping that I can do this without having to implement half a dozen comparison methods like

int compare(System::String ^ s1, char * s2);
int compare(System::String ^ s1, wchar_t * s2);
int compare(System::String ^ s1, std::string s2);
int compare(System::String ^ s1, std::wstring s2);
int compare(char * s1, System::String ^ s2);
int compare(wchar_t * s1, System::String ^ s2);
...

The primary purpose will be equality comparisons, so if those are significantly easier to do, 开发者_高级运维then I would like to see those answers as well.


Here's an excellent MSDN article covering this topic in both directions:

http://msdn.microsoft.com/en-us/library/42zy2z41.aspx

And here's the Marshal class:

http://msdn.microsoft.com/en-us/library/atxe881w.aspx

With this, I would suggest defining various managed code methods that take the different types of native strings, converts them into a managed string, then compares them.

Unfortunately, I see no way to get around permutating the different native string types. They are literally different data types, even though they both represent what we call a string. And if it messes up the conversion, you can get into some dangerous territory.

Also, I would drop std::string out of the running, since you can easily call c_str() to get a const char * out. Same for std::wstring and wchar_t.

Here's an example of one:

using namespace System::Runtime::InteropServices;

public static int NativeCompare(System::String ^ s1, char * s2)
{
    System::String ms2 = Marshal::PtrToStringAnsi((IntPtr)s2);
    return s1.CompareTo(ms2);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号