我正在处理 C# 代码中的 char*(在不安全部分)。有什么方法可以从 C# 调用 strlen 函数。必须编写自定义 strlen 函数来搜索空终止符是违反所有常识的。有没有办法从 C# 或我有权访问的类似方法调用 strlen?
总的来说,我正在尝试将 char* 转换为字符串对象,但字符为 ANSCII 格式,因此我将使用 .NET Encoding.Convert 命名空间对其进行转换。但在我这样做之前我需要知道字符串的长度。
最佳答案
Marshal.PtrToStringAnsi()
完全满足您的需求:
Allocates a managed String and copies all characters up to the first null character from a string stored in unmanaged memory into it.
顺便说一句,该方法在指针上调用了lstrlenA
,这实际上只是从kernel32.dll
导入。换句话说,没有似乎有一个托管的“让我知道这个非托管字符串的长度”方法可用。
关于c# - 在 C# 中处理 char*(strlen 函数?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112794/