【问题标题】:How to compare managed and unmanaged Strings?如何比较托管和非托管字符串?
【发布时间】:2010-07-23 14:21:21
【问题描述】:

我有一个应用程序在 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);
...

主要目的是进行相等比较,所以如果这些比较容易做到,那么我也希望看到这些答案。

【问题讨论】:

    标签: string visual-c++ .net-2.0


    【解决方案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::wstringwchar_t 相同。

    这是一个例子:

    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);
    }
    

    【讨论】:

    • 是否有任何特别的理由选择使用 System::String 进行比较而不是任何替代方案?我不知道使用 C 风格的字符串是否会更好,但我无法想象它会更糟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 2010-09-11
    • 2011-10-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    相关资源
    最近更新 更多