c#调用delphi开发的dll的指针参数

来源:互联网 发布:js tostring 参数 编辑:程序博客网 时间:2024/05/18 13:26

在c#中调用DELPH编写的DLL的函数时出现未将对象引用到实例的错误: delphi编写的dll中函数声明:function DeliverfromEsm(var Smtype, Content,Caller:pchar):integer;

Content:短信内容或报告(若Smtype为即时消息或离线消息,则Content表示短信内容;否则,Content表示返回的状态报告情况);   Content表示返回的状态报告Report结构:     DWORD TaskID; //客户端序列号 TaskID     DWORD MsgID; //客户端序列号 MsgID     char UserNumber[22]; //接收手机号     unsigned char state; //状态     unsigned char ErrCode; //错误代码 我在c#中声明: [DllImport("EsmApi.dll",CharSet  =  CharSet.Ansi,CallingConvention  =  CallingConvention.StdCall)] static extern int DeliverfromEsm(ref string smtype,ref string content,ref string caller); 调用: string smtype=""; string content=""; string caller=""; int reportval=DeliverfromEsm( ref smtype,ref content,ref caller); 出现未将对象引用到实例的错误

以下是解决办法:

声明:

[DllImport("EsmApi.dll",CharSet   =   CharSet.Ansi,CallingConvention   =   CallingConvention.StdCall)]   static extern int DeliverfromEsm(StringBuilder Smtype, IntPtr Content,StringBuilder Caller);//接收短信和report

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)]   public struct Report   {    public int TaskID;//4byte    public int MsgID;    [MarshalAs(UnmanagedType.ByValTStr,SizeConst=22)]public string UserNumber;    public byte state;//1byte    public byte ErrCode;   }

程序中处理:

StringBuilder   smtype=   new   StringBuilder(256);//Init   buffer          

    int size = Marshal.SizeOf(typeof(Report));     IntPtr content=Marshal.AllocHGlobal(size);//分配32bytes     StringBuilder   caller=   new   StringBuilder(256);//Init   buffer     int reportval=DeliverfromEsm(  smtype,content, caller);

//字符串时

string smscontent=Marshal.PtrToStringAnsi(content);

//结构体时

Report content1=(Report)Marshal.PtrToStructure(content,typeof(Report));

Marshal.FreeHGlobal(content);//释放

参考了网上的一段代码:

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]    public struct VideoCompressorInfo    {        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]        public string szName;        public Int32 dwHandle;    }        [DllImport("DSStream.dll")]        public extern static int DSStream_EnumVideoCompressor(IntPtr pInfo, ref int piVidCompNum);             int num = 0;            DSStream_EnumVideoCompressor(IntPtr.Zero, ref num);            int size = Marshal.SizeOf(typeof(VideoCompressorInfo));            IntPtr structPtr = Marshal.AllocHGlobal(size * num);            DSStream_EnumVideoCompressor(structPtr, ref num);            VideoCompressorInfo[] infos = new VideoCompressorInfo[num];            for (int i = 0; i < num; ++i)            {                infos[i] = (VideoCompressorInfo)Marshal.PtrToStructure((IntPtr)((int)structPtr + i * size), typeof(VideoCompressorInfo));            }            Marshal.FreeHGlobal(structPtr);

原创粉丝点击