为什么 C#/.NET 字符串带有长度前缀并以 null 结尾?

发布于 2024-11-14 19:57:43 字数 319 浏览 10 评论 0原文

阅读空终止字符串的基本原理是什么?和一些类似的问题后我发现在 C#/.NET 字符串内部,长度前缀和 null 终止,就像 BSTR 数据类型

字符串都带有长度前缀和空终止而不是例如的原因是什么?仅长度前缀?

After reading What's the rationale for null terminated strings? and some similar questions I have found that in C#/.NET strings are, internally, both length-prefixed and null terminated like in BSTR Data Type.

What is the reason strings are both length-prefixed and null terminated instead of eg. only length-prefixed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

成熟稳重的好男人 2024-11-21 19:57:43

长度前缀,以便计算长度为O(1)

空终止以使编组到非托管的速度非常快(非托管可能需要空终止字符串)。

Length prefixed so that computing length is O(1).

Null terminated to make marshaling to unmanaged blazing fast (unmanaged likely expects null-terminated strings).

叹沉浮 2024-11-21 19:57:43

以下是 Jon Skeet 的博客 帖子 关于字符串的摘录:

虽然就 API 而言,字符串不是以 null 结尾的,但字符数组是以 null 结尾的,因为这意味着它可以直接传递给非托管函数,而不涉及任何复制,假设互操作指定该字符串应编组为 Unicode。

Here is an excerpt from Jon Skeet's Blog Post about strings:

Although strings aren't null-terminated as far as the API is concerned, the character array is null-terminated, as this means it can be passed directly to unmanaged functions without any copying being involved, assuming the inter-op specifies that the string should be marshalled as Unicode.

鲸落 2024-11-21 19:57:43

最有可能的是,为了确保与 COM 的轻松互操作性。

Most likely, to ensure easy interoperability with COM.

我不会写诗 2024-11-21 19:57:43

虽然长度字段使框架可以轻松确定字符串的长度(并且它允许字符串包含零值的字符),但框架(或用户程序)需要处理大量的内容以 NULL 结尾的字符串。

例如,像 Win32 API。

因此,在字符串数据末尾保留 NULL 终止符很方便,因为无论如何它可能需要经常出现。

请注意,C++ 的 std::string 类以相同的方式实现(无论如何在 MSVC 中)。出于同样的原因,我确信(c_str() 通常用于将 std::string 传递给需要 C 风格字符串的对象)。

While the length field makes it easy for the framework to determine the length of a string (and it lets string contain characters with a zero value), there's an awful lot of stuff that the framework (or user programs) need to deal with that expect NULL terminated strings.

Like the Win32 API, for example.

So it's convenient to keep a NULL terminator on at the end of the string data because it's likely going to need to be there quite often anyway.

Note that C++'s std::string class is implemented the same way (in MSVC anyway). For the same reason, I'm sure (c_str() is often used to pass a std::string to something that wants a C-style string).

瑾夏年华 2024-11-21 19:57:43

最好的猜测是,与遍历长度相比,找到长度是恒定的 (O(1)),运行时间为 O(n)。

Best guess is that finding the length is constant (O(1)) compared to traversing it, running in O(n).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文