C# 调用 C++ dll,数组输出方法

C# 调用 C++ dll,数组输出方法

老是忘记,故记录下下,以输出 char* 为例:

C++:
extern “C” __declspec(dllexport) int GetEmail(char *pEmail); //用 pEmail 输出数据。

C#:
方法一:

[DllImport(dllPath, CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetEmail")]
        public static extern int GetEmail(IntPtr pEmail);

public bool GetEmailString(ref string pEmail)
        {
            //开辟空间,用于输出数据
            IntPtr email_ = Marshal.AllocHGlobal(1024);
            int len =  GetEmail(email_); //输出的数据会存储到 email_ 中
            if (len > 0)
            {
                byte[] email = new byte[len]; 
                //email_ 转到 C# 的email.
                Marshal.Copy(email_, email, 0, len);
                pEmail= System.Text.Encoding.Default.GetString(email);
                return true;
            }
            return false;
        }

方法二:

[DllImport(dllPath, CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetEmail")]
        public static extern int GetEmail(ref byte pEmail);

public bool GetEmailString(ref string pEmail)
        {
            byte[] email = new byte[1024];
            int len =  GetEmail(ref email[0]); //这样输出的数据都会存储到 email 中
            if (len > 0)
            {
                byte[] email_ = new byte[len];
                for (int i = 0; i < len; i++) { email_[i] = email[i]; }
                pEmail= System.Text.Encoding.Default.GetString(email_);
                return true;
            }
            return false;
        }

你可能感兴趣的:(C#)