Usage of CoTaskMemAlloc?

后端 未结 5 1552
攒了一身酷
攒了一身酷 2020-12-06 01:12

When is it appropriate to use CoTaskMemAlloc? Can someone give an example?

5条回答
  •  暖寄归人
    2020-12-06 01:39

    Use CoTaskMemAlloc when returning a char* from a native C++ library to .NET as a string.

    C#

    [DllImport("test.dll", CharSet=CharSet.Ansi)]
    extern static string Foo();
    

    C

    char* Foo()
    {
        std::string response("response");
        int len = response.length() + 1;
        char* buff = (char*) CoTaskMemAlloc(len);
        strcpy_s(buff, len, response.c_str());
        return buff;
    }
    

    Since .NET uses CoTaskMemFree, you have to allocate the string like this, you can't allocate it on the stack or the heap using malloc / new.

提交回复
热议问题