【问题标题】:C# Equivalent for PtrToStringChars(String s) function present in vcclr.hC# 等效于 vcclr.h 中存在的 PtrToStringChars(String s) 函数
【发布时间】:2013-08-15 14:33:13
【问题描述】:

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

该文件是 vcclr.h,它位于 Visual Studio 9.0/VC/include 文件夹中。函数是PtrToStringChars(string s)

是否有一个等效的 c# 函数可以用来代替这个原生 C++ 函数?

另外,如果我想导入这个函数,我需要指定包含这个文件的 dll 的名称。如何获取这个 dll 的名称?

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

【问题讨论】:

  • 也许你给我们函数的名字?
  • 函数名是 vcclr.h 文件中的 PtrToStringChars(string s)

标签: c# c++ visual-studio dll


【解决方案1】:

你不需要那个方法:

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 行用于 cmets,40-48 用于代码)。

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多