Is it possible to get a pointer to an internal String ^ array in C ++ / CLI?

The goal is to avoid copying string data when I need to const wchar_t*.

The answer seems to be yes, but the function PtrToStringCharsdoes not have its own MSDN record (it is only mentioned in KB and blogs as a trick). It made me suspicious, and I want to check with you guys. Is it safe to use this feature?

+3
source share
3 answers

Yes, not a problem. This is actually somewhat documented , but hard to find. MSDN docs for C ++ libraries are small. It returns an internal pointer that is not yet suitable for conversion to const wchar_t *. You must attach a pointer so that the garbage collector cannot move the string. Use pin_ptr <> for this.

You can use Marshal :: StringToHGlobalUni () to create a copy of the string. Use this instead if wchar_t * should remain valid for a long period of time. Extending objects for too long is not very useful for the garbage collector.

+2
source

, PtrToStringChars, , C:

wchar_t *ManagedStringToUnicodeString(String ^s)
{
    // Declare
    wchar_t *ReturnString = nullptr;
    long len = s->Length;

    // Check length
    if(len == 0) return nullptr;

    // Pin the string
    pin_ptr<const wchar_t> PinnedString = PtrToStringChars(s);

    // Copy to new string
    ReturnString = (wchar_t *)malloc((len+1)*sizeof(wchar_t));
    if(ReturnString)
    {
        wcsncpy(ReturnString, (wchar_t *)PinnedString, len+1);
    }

    // Unpin
    PinnedString = nullptr;

    // Return
    return ReturnString;
}
+3

According to this article: http://support.microsoft.com/kb/311259 PtrToStringChars is officially supported and can be used. It is described as "getting the internal gc pointer for the first character contained in the System :: String object" in the vcclr.h file.

0
source

Source: https://habr.com/ru/post/1750133/


All Articles