我有一个本机C++函数,希望将其导入到C#项目文件中。
该文件为vcclr.h,其存在于VisualStudio9.0/VC/include文件夹中。功能是PtrToStringChars(string s)
我能用一个等价的c#函数来代替这个本机C++函数吗?
另外,如果我想导入这个函数,我需要指定包含这个文件的dll的名称。如何获得这个dll的名称?
我可以看到包含这个函数的C++文件,从那里我可以看到它的文件夹位置(绝对路径和相对路径)。
发布于 2013-08-15 14:39:40
你不需要那种方法:
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行是代码)。
https://stackoverflow.com/questions/18254989
复制相似问题