我有与 C++ 代码交互的 C# 代码,它使用字符串执行操作。
我在静态助手类中有这段代码:
internal static unsafe byte* GetConstNullTerminated(string text, Encoding encoding)
{
int charCount = text.Length;
fixed (char* chars = text)
{
int byteCount = encoding.GetByteCount(chars, charCount);
byte* bytes = stackalloc byte[byteCount + 1];
encoding.GetBytes(chars, charCount, bytes, byteCount);
*(bytes + byteCount) = 0;
return bytes;
}
}
如您所见,它返回一个指向使用stackalloc
关键字创建的字节的指针。
但是从 C# Specifications 18.8 开始:
在函数成员执行期间创建的所有堆栈分配内存块都会在该函数成员返回时自动丢弃。
这是否意味着一旦方法返回,指针实际上就无效了?
该方法的当前用法:
byte* bytes = StringHelper.GetConstNullTerminated(value ?? string.Empty, Encoding);
DirectFunction(NativeMethods.SCI_SETTEXT, UIntPtr.Zero, (IntPtr) bytes);
代码是否应该更改为
...
int byteCount = encoding.GetByteCount(chars, charCount);
byte[] byteArray = new byte[byteCount + 1];
fixed (byte* bytes = byteArray)
{
encoding.GetBytes(chars, charCount, bytes, byteCount);
*(bytes + byteCount) = 0;
}
return byteArray;
并fixed
在返回的数组上再次使用,将指针传递给DirectFunction
方法?
我试图尽量减少使用次数fixed
(包括fixed
其他重载 ofGetByteCount()
和GetBytes()
of中的语句Encoding
)。
tl;博士
方法返回后指针是否无效?它在传递给时是否无效
DirectFunction()
?如果是这样,使用最少的
fixed
语句来完成任务的最佳方法是什么?