如何比较托管和非托管字符串?
我有一个应用程序,它在 UI 元素中使用托管 System::String
,但随后引用非托管(读取:遗留)代码来进行更复杂的计算。
此外,字符串的编码不一致 - 托管字符串可以是常规 "strings"
或 Unicode L"strings"
,非托管字符串可以是所有字符串char *、wchar_t *、std::string、std::wstring
品种。
比较各种琴弦风格的最佳方法是什么?我希望我可以做到这一点,而不必实现六个比较方法,例如
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);
...
主要目的是相等比较,所以如果这些方法更容易做到,那么我也想看到这些答案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一篇优秀的 MSDN 文章,从两个方向涵盖了该主题:
http://msdn。 microsoft.com/en-us/library/42zy2z41.aspx
这是 Marshal 类:
http://msdn.microsoft.com/en-us/library/atxe881w.aspx
有了这个,我建议定义各种托管代码方法,这些方法采用不同类型的本机字符串,将它们转换转换为托管字符串,然后对它们进行比较。
不幸的是,我认为没有办法绕过排列不同的本机字符串类型。它们实际上是不同的数据类型,尽管它们都表示我们所说的字符串。如果它扰乱了转换,您可能会陷入危险的境地。
另外,我会将
std::string
排除在运行之外,因为您可以轻松调用c_str()
来获取const char *
。std::wstring
和wchar_t
相同。这是一个例子:
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 callc_str()
to get aconst char *
out. Same forstd::wstring
andwchar_t
.Here's an example of one: