开发者

Easiest way to pass modifyable System.String as modifyable LPTSTR?

开发者 https://www.devze.com 2023-01-04 10:21 出处:网络
BOOL PathFindOnPath(LPTSTR pszFile, LPCTSTR *ppszOtherDirs ); I am calling this API from managed C++. My pszFile is in a System.String.

BOOL PathFindOnPath( LPTSTR pszFile, LPCTSTR *ppszOtherDirs );

I am calling this API from managed C++. My pszFile is in a System.String.

What is the easiest way to pass this as LPTSTR? (Considering its an inout parameter)

I have 开发者_JAVA百科tried pin_ptr and interior_ptr but neither seems to be accepted by the compiler.


You need to marshal across a (pre-allocated) StringBuilder instead of a String reference. For details, see this MSDN article on Marshaling.


Strings are immutable, you cannot pass it directly, even if you pin it. More seriously, you will have to deal with the possibility that the function returns a larger string. The function is unsafe by design since you cannot prevent it from returning a path string that's too large. Not much you can do about that I suppose, but you will have to use a buffer that's at least large enough for common path strings. This code will get the job done:

#include <vcclr.h>
...
    String^ file = "blah.txt";
    wchar_t path[_MAX_PATH];
    {
        pin_ptr<const wchar_t> wch = PtrToStringChars(file);
        wcscpy_s(path, _MAX_PATH, wch);
    }
    BOOL ok = PathFindOnPath(path, something);

The curly braces look odd perhaps, it ensures that the managed string doesn't stay pinned for too long.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号