C#调用 非托管C++ dll 传入Stringbuilder、ref string 、 ref char 等都报错,如mscorlib.dll 异常、其他信息: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏 等等,后来发现是dll 生成后一直没更新,放错位置了。。。 = =||
不过也学习了一下编译器及类型相关的知识,整理如下:
1、 cl.exe /Gz 参数指定编译为 __stdcall 调用方式,默认为 __cdecl
2、C#中的char是两个字节
http://msdn.microsoft.com/zh-cn/library/x9h8tsay(v=vs.80).aspx
类型范围大小.NET Framework 类型
charU+0000 到 U+ffff16 位 Unicode 字符System.Char
类型范围大小.NET Framework 类型
byte0 到 255无符号 8 位整数System.Byte
3、C++ dll 类型与 C#类型对应关系
参考:
本以为这篇搜集整理的代码会是很不错的文章,花了一天时间,搜索到最后居然出来一篇叫做"C# 与 C++ 数据类型对照表"的文章.几乎囊括掉和大部分的数据了,太打击我了. 本文中有部分的数据没有测试.也有一些不错的是看了上百篇网文对比整理得来的.希望有帮助.
//C++中的DLL函数原型为
//extern "C" __declspec(dllexport) bool 方法名一(const char* 变量名1, unsigned char* 变量名2)
//extern "C" __declspec(dllexport) bool 方法名二(const unsigned char* 变量名1, char* 变量名2)
//C#调用C++的DLL搜集整理的所有数据类型转换方式,可能会有重复或者多种方案,自己多测试
//c++:HANDLE(void *) ---- c#:System.IntPtr
//c++:Byte(unsigned char) ---- c#:System.Byte
//c++:SHORT(short) ---- c#:System.Int16
//c++:WORD(unsigned short) ---- c#:System.UInt16
//c++:INT(int) ---- c#:System.Int16
//c++:INT(int) ---- c#:System.Int32
//c++:UINT(unsigned int) ---- c#:System.UInt16
//c++:UINT(unsigned int) ---- c#:System.UInt32
//c++:LONG(long) ---- c#:System.Int32
//c++:ULONG(unsigned long) ---- c#:System.UInt32
//c++:DWORD(unsigned long) ---- c#:System.UInt32
//c++:DECIMAL ---- c#:System.Decimal
//c++:BOOL(long) ---- c#:System.Boolean
//c++:CHAR(char) ---- c#:System.Char
//c&