C# 调用Delphi 方法 指针参数处理

C#项目调用 Delphi 方法,其中

Delphi 声明:

function SendEx(AName,ACommand,AContent:PAnsiChar;var AResult:PAnsiChar):Boolean; stdcall;

测试  参数使用 string,stringBulider,IntPtr,string[] 都无果

============================重点开始==========================

IntPtr Test= Marshal.StringToHGlobalAnsi("Test");//错误

========》正确:Test=mallocIntptr("Test");

原因不晓得,有空在去了解;

============================重点结束==========================

C#:

 [DllImport(@"E:\Test.dll", EntryPoint = "SendEx", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
  public static extern Boolean SendEx(IntPtr AName, IntPtr ACommand, IntPtr AContent, ref IntPtr AResult);

调用:

 

  private void IPC_IntPtr_Delphi_Click(object sender, EventArgs e)
        {
            try
            {
                IntPtr AServerName, ACommand, AContent, AResult;
                //SendEx("MyTestIPC", "Command", "测试", ref AResult);
                //根据数据的长度申请非托管空间   
                AName = mallocIntptr("MyTestIPC");
                ACommand = mallocIntptr("Command");
                AContent = mallocIntptr("测试---IntPtr--");
                AResult = mallocIntptr("测试---IntPtr--");
                bool res = SendEx(AName, ACommand, AContent, ref AResult);
                if (res) { string sss = Marshal.PtrToStringAnsi(AResult); }
                Marshal.FreeHGlobal(AName);
                Marshal.FreeHGlobal(ACommand);
                Marshal.FreeHGlobal(AContent);
                Marshal.FreeHGlobal(AResult);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }

        /// <summary>   
        /// 根据数据的长度申请非托管空间   
        /// </summary>   
        /// <param name="strData">要申请非托管空间的数据</param>   
        /// <returns>指向非拖管空间的指针</returns>   
        private static IntPtr mallocIntptr(string strData)
        {
            //先将字符串转化成字节方式   
            Byte[] btData = System.Text.Encoding.Default.GetBytes(strData);

            //申请非拖管空间   
            IntPtr m_ptr = Marshal.AllocHGlobal(btData.Length);

            //给非拖管空间清0    
            Byte[] btZero = new Byte[btData.Length + 1]; //一定要加1,否则后面是乱码,原因未找到   
            Marshal.Copy(btZero, 0, m_ptr, btZero.Length);

            //给指针指向的空间赋值   
            Marshal.Copy(btData, 0, m_ptr, btData.Length);

            return m_ptr;
        }

   /// <summary>   
        /// 根据长度申请非托管空间   
        /// </summary>   
        /// <param name="strData">要申请非托管空间的大小</param>   
        /// <returns>指向非拖管空间的指针</returns>  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值