做的IntPtr在C#.NET指向字符串值字符串值、IntPtr、NET

2023-09-03 16:08:25 作者:淺憶︿夢微涼

我使用的有 StringHandle 字段,它是一个的IntPtr 值重新presents一类 LPCWSTR 在C ++中。

I am using a class which has StringHandle field which is an IntPtr value that represents a LPCWSTR in C++.

internal IntPtr StringHandle; // LPCWSTR

说现在我有一个字符串:字符串x =ABCDEFG

如何使用String把手指向字符串的开头,这样它像C ++ LPCWSTR?

How can I use the String handle to point to the beginning of the String so that it is like C++ LPCWSTR ?

推荐答案

您需要将字符串复制到非托管内存,然后再拿到的IntPtr 从该位置。你可以这样做喜欢的:

You need to copy the string to the unmanaged memory first and then get the IntPtr from that location. You can do so like:

IntPtr strPtr = Marshal.StringToHGlobalUni(x);

此外,您还需要确保以释放非托管内存:

also, you need to make sure to free the unmanaged memory:

Marshal.FreeHGlobal(strPtr);

这是最好的做这一切在一个try /最后。

it's best to do all this in a try/finally.