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>