指针的概念
指针是一个特殊的变量,它里面存储的数值被解释成为内存里的一个地址。要搞清一个指针需要搞清指针的四方面的内容:指针的类型,指针所指向的类型,指针的值或者叫指针所指向的内存区,还有指针本身所占据的内存区。让我们分别说明。
先声明几个指针放着做例子:
例一:
int *ptr;
char *ptr;
int **ptr;
int (*ptr)[3];
int *(*ptr)[4];
正文
1、背景
在c++代码中定义了一个功能函数,这个功能函数会将计算的结果写入一个字符串型的数组中output
,然后c#会调用c++导出的dll中的接口函数,然后获取这个output
并解析成string类型。
2、实例
c++:
cppdll_api int function( char*& output)
c#:
[dllimport(@"project1.dll", entrypoint = "function",charset = charset.auto)] public static extern int function(ref intptr output); intptr ptr = intptr.zero; int isok = function(ref ptr); // -> unicode byte[] bytes = system.text.encoding.unicode.getbytes(marshal.ptrtostringuni(ptr)); // -> utf8 string dec = system.text.encoding.utf8.getstring(bytes);
错误代码:
string dec = marshal.ptrtostringansi(ptr);
得到的dec是乱码,查询发现是因为内存编码是utf8,marshal不支持utf转换,所以必须先转成unicode再转成utf8。
到此这篇关于c#解析char型指针所指向的内容的文章就介绍到这了,更多相关c# char指针内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论