C#和C混合编程——调用dll中函数返回值为字符串地址

因为C#不支持地址,调用dll函数中若函数返回值为字符串地址的处理方式:
1、dll中封装的函数为:

char * communication(char * str)

2、在C#中声明:

 [DllImport("client_dll1.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr communication(string str);

注意,即communication函数返回值类型char*对应在C#中使用IntPtr,变量类型char*对应在C#中使用string

3、调用函数后肯定希望得到的是字符串调用函数Marshal.PtrToStringAnsi()进行转换,例如,我的代码中完成的是按下回车,获取textout文本框内容,调用communication,得到IntPtr类型的rcve,再将其转换为string类型在textin文本框中显示

 private void textout_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;
            string inputt, stringrcve;

            if (ch == '\r')
            {
                inputt = textout.Text;
                IntPtr rcve = communication(inputt);
                stringrcve = Marshal.PtrToStringAnsi(rcve);
                textin.Text = stringrcve;
                }
        }

猜你喜欢

转载自blog.csdn.net/weixin_43428892/article/details/106803005