none
Passing strings over dll boundaries. RRS feed

  • Question

  •  Hi all,

    This a problem about windows dll.

    I wrote a dll export this API to learn how strings are passed over the dll boundaries.

    extern "C" PINVOKELIB_API char * TestStringAsResult()
    {
       STRSAFE_LPWSTR result = (STRSAFE_LPWSTR)CoTaskMemAlloc( 1000 * 1000 * 100 );
       StringCchCopy( result, 1000 , (STRSAFE_LPWSTR)"This is return value" );
       return (char *) result;
    }

    In my opinion,  as the function allocated memory but do not release it, any call of it would leak 100M bytes memory.

    But when I call it though DLLImport provieded by .net framework,  that doesn't happen!
     
    Is there some mechanism that automatically release memory of string passed over dll boundaries?

    Thanks a lot!


    ablmf
    Sunday, August 24, 2008 9:14 AM

Answers

  • The P/Invoke marshaller knows that the memory for the string needs to be released.  There's no way for the managed app to do it.  So it calls Marshal.FreeCoTaskMem().  You picked the exact allocator you needed to use, I assume it wasn't luck.  You'd have an entirely different kind of problem if you returned a const char*, that crashes on Vista (but not XP).
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Thursday, August 28, 2008 9:12 AM
    Sunday, August 24, 2008 6:10 PM
    Moderator

All replies

  • The P/Invoke marshaller knows that the memory for the string needs to be released.  There's no way for the managed app to do it.  So it calls Marshal.FreeCoTaskMem().  You picked the exact allocator you needed to use, I assume it wasn't luck.  You'd have an entirely different kind of problem if you returned a const char*, that crashes on Vista (but not XP).
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Thursday, August 28, 2008 9:12 AM
    Sunday, August 24, 2008 6:10 PM
    Moderator
  • Hi, you are right.  I got this example from msdn.

    Do u mean that the "The P/Invoke marshaller" freed the memory automatically?

    ---------------------------------------------

    If this is case happened in .net,  what about native C++.

    If I use the dll from native C++ code, should I call FreeCoTaskMem myself?

    Thanks a lot!
    ablmf
    Monday, August 25, 2008 1:30 AM
  • Yes, nothing is automatic in C++.
    Hans Passant.
    Monday, August 25, 2008 7:31 AM
    Moderator