积极答复者
C++中的CHAR* 在C#里应该用什么类型表示?

问题
-
C++里头定义: CHAR *Url_Name;
C#里头定义: public ushort[] Url_Name;
赋值Url_Name= StringToShortArray_(“http://127.0.0.1/test.aspx”,"ANSI");
// 根据字符编码类型,把字符串转化成ushort[],一个中文对应一个ushort值 public static ushort[] StringToShortArray_(string value, string charaterSet) { char[] words = value.ToCharArray(); ushort[] target = new ushort[words.Length]; for (int i = 0; i < words.Length; i++) { if (IsGBCode(words[i])) { byte[] bValues = string2bytes(words[i].ToString(), charaterSet); target[i] = (ushort)(((bValues[0] & 0xff) << 8) | bValues[1]); } else { target[i] = ushort)words[i]; } } return target; } public static byte[] string2bytes(string data, string charaterSet)
{
if (data == null || data == string.Empty) throw new Exception("");
return Encoding.GetEncoding(charaterSet).GetBytes(data);
}运行,报错如下:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
我只好修改代码如下:
C#定义部分
//using System.Runtime.InteropServices; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public ushort[] Url_Name;
运行后,出错,提示数组大小不匹配 Type could not be marshaled because the length of an embedded array instance does not match the declared length in the layout.
只好修改到大小为26,正好匹配,但是以后传这个参数怎么办?先不管了,修改再说。[MarshalAs(UnmanagedType.ByValArray, SizeConst = 26)] 结果还是一开始的问题Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
c++的char* 对应c#应该是无符号int16,也就是ushort啊,但是c++里头运行时好像不是数组,我这边定义数组是不是有问题?还有,用C#里头的ushort.Parse(<a href="http://127.0.0.1/test.aspx">http://127.0.0.1/test.aspx</a>);
报错说Input string was not in a correct format. 纠结了,不知道怎么转,无法理解字符串被转换成一个无符号16位int。
向大家求救~~~
答案
-
char* 在 C# 里默认被当成 string。如果从理论上讲,char 在 C++ 中是无符号单字节,即 0-255。对应于 C# 的 byte。
不过各种不同的 char* 可能需要附加 MarshalAs 属性 (Attribute),因为 C++ 会有很多基于 char* 的类型出来,像 LPSTR, LPCSTR, LPCTSTR, TCHAR 等等。
建议先参考 string 以及 MarshalAs。
Mark Zhou- 已标记为答案 KeFang Chen 2010年4月9日 2:54
全部回复
-
我试了下,用byte数组,还是报错Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
我用UTF8Encoding.UTF8.GetBytes(http://127.0.0.1/test.aspx);转成byte数组了,好像类型还是不太正确。不知道该用什么类型了。char*不能在C#中用,也不知道怎么转换,头疼啊。
-
char* 在 C# 里默认被当成 string。如果从理论上讲,char 在 C++ 中是无符号单字节,即 0-255。对应于 C# 的 byte。
不过各种不同的 char* 可能需要附加 MarshalAs 属性 (Attribute),因为 C++ 会有很多基于 char* 的类型出来,像 LPSTR, LPCSTR, LPCTSTR, TCHAR 等等。
建议先参考 string 以及 MarshalAs。
Mark Zhou- 已标记为答案 KeFang Chen 2010年4月9日 2:54