When to use SafeArrayAccessData to lock a SAFEARRAY

旧街凉风 提交于 2020-01-24 18:58:39

问题


I'm having a question about when it is necessary to use SafeArrayAccessData to lock a SAFEARRAY, which is passed by managed code. Here is our code. The VARIANT is passed by managed code, with a string array. During code review, somebody suggest to use SafeArrayAccessData/SafeArrayUnAccessData. But he is not sure about why and what's the benefit. Can you share some of your experiences? Thanks!

STDMETHODIMP Base::Method1(VARIANT values, VARIANT_BOOL result)
{
    CComSafeArray<BSTR> ids;
    ids.Attach(values.parray);

    unsigned int size = ids.GetCount();
    for(unsigned int i = 0; i < size; ++i)
    {
    // use ids[i] here
    }
    // ...
}

回答1:


Well, always :) You need it to get a reference to the array content.

But you use a friendly C++ wrapper class. The CComSafeArray<> template already does this for you so you should not help. It uses SafeArrayLock() in the Attach() method, that also returns a pointer to the array content like SafeArrayAccessData() does. And automatically unlocks with its destructor, it runs at the end of your method. Locking otherwise ensures that the array access is thread-safe and cannot be deleted while you are accessing it. There is little danger of that in your existing code, but this squarely fits the better-safe-than-sorry principles of Automation.



来源:https://stackoverflow.com/questions/17229106/when-to-use-safearrayaccessdata-to-lock-a-safearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!