我有一个本机C ++函数,我希望将其导入到我的C#项目文件中。
该文件是vcclr.h,它存在于Visual Studio 9.0 / VC / include文件夹中。该函数为PtrToStringChars(string s)
我是否可以使用等效的c#函数代替这个本机C ++函数?
另外,如果我想导入此函数,我需要指定包含此文件的dll的名称。我如何获得此dll的名称?
我可以看到包含此功能的C ++文件,从那里我可以看到它的文件夹位置(绝对路径和相对路径)。
答案 0 :(得分:3)
您不需要该方法:
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 Statement):
fixed (char* ptr2 = str)
{
char ch2 = *ptr2;
}
如果你想要完全 PtrToStringChars(...)
怎么办?你不能拥有它......它直接在vcclr.h
标题中定义为内联函数(在我的第37-39行中为注释,40-48为代码)。