vcclr.h中存在的PtrToStringChars(Strings)函数的C#等价项

本文关键字:函数 存在 PtrToStringChars vcclr Strings | 更新日期: 2023-09-27 18:27:44

我有一个本机C++函数,我希望将其导入到我的C#项目文件中。

该文件为vcclr.h,位于Visual Studio 9.0/VC/include文件夹中。功能为PtrToStringChars(string s)

有没有一个等效的c#函数可以代替这个原生c++函数?

此外,如果我希望导入此函数,我需要指定包含此文件的dll的名称。如何获取此dll的名称?

我可以看到包含这个函数的C++文件,从那里我可以看到它的文件夹位置(绝对和相对路径)。

vcclr.h中存在的PtrToStringChars(Strings)函数的C#等价项

您不需要该方法:

string str = "hello".Substring(0, 2); // force not to inline the string
                                      // it would be the same if it was inlined
GCHandle h = GCHandle.Alloc(str, GCHandleType.Pinned);
IntPtr ptr = h.AddrOfPinnedObject(); // Your address
// ch is h
// the unchecked is necessary (technically optional because it's default)
// because Marshal.ReadInt16 reads a signed Int16, while char is more similar
// to an unsigned Int16
char ch = unchecked((char)Marshal.ReadInt16(ptr));

或者带有一点不安全的代码(参见固定语句):

fixed (char* ptr2 = str)
{
    char ch2 = *ptr2;
}

如果您想要恰好PtrToStringChars(...),该怎么办?你不能拥有它…它直接在vcclr.h标题中定义为内联函数(在我的第37-39行中用于注释,40-48行用于代码)。