使用字符串声明BSTR [英] Assert a BSTR with string

查看:96
本文介绍了使用字符串声明BSTR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下测试功能:

    [TestMethod]
    void RipMichaelJacksonTest()
    {
        string expected = "Hello";
        BSTR actual = SysAllocString(L"Hello");
        Assert::AreEqual(expected, actual);
    }

assert部分当然会失败.

我可以使用任何Assert函数吗? 我是VC ++的新手.

Is there any Assert function that i can use? Im new to VC++.

推荐答案

问题是您正在执行 AreEqual(Object^, Object^) 其中:

The problem is that you are doing a AreEqual. Passing in two parameters will force AreEqual(Object^, Object^) which:

验证两个指定的对象是否相等.如果对象不相等,则断言将失败.

Verifies that two specified objects are equal. The assertion fails if the objects are not equal.

您真正要寻找的是wchar*char*的比较.两者之间没有直接比较功能,因此有必要将string转换为wstring.有关如何执行此操作的示例很多,例如: https://stackoverflow.com/a/7159944/2642059,并且您需要执行类似的操作,例如:

What you are actually looking for is the comparison of a wchar* and a char*. There is not a direct comparison function between the two so it will be necessary to convert from a string to a wstring. There are lots of examples of how to do that, such as: https://stackoverflow.com/a/7159944/2642059 and you'll need to do something similar, for example:

wstring get_wstring(const string& s) {
    wstring buf;
    const char* cs = s.c_str();
    const size_t wn = mbsrtowcs(nullptr, &cs, 0, nullptr);

    if (wn == string::npos) {
        cout << "Error in mbsrtowcs(): " << errno << endl;
    } else {
        buf.resize(wn + 1);

        if(mbsrtowcs(&*buf.begin(), &cs, wn + 1, nullptr) == string::npos) {
            cout << "Error in mbsrtowcs(): " << errno << endl;
            buf.resize(0);
        }
    }

    return buf;
}

get_wstring(expected)actual的返回值现在都将是wchar,因此可以在使用

The return of get_wstring(expected) and actual will now both be wchars and can thereby be compared in the using AreEqual(String^, String^, bool)

这篇关于使用字符串声明BSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆