C#调用c库DLL异常

使用c#调用C库 :

C声明:

DECLDIR int  test (char* param, char *tokenId, char *retMessage, int *retLen);


声明代码:

using System.Runtime.InteropServices;
[DllImport("xxx.dll", CallingConvention = CallingConvention.Cdecl)]
internal static extern int test(IntPtr param, IntPtr tokenId, IntPtr retMessage, ref int retLen);



C#中的IntPtr类型称为“平台特定的整数类型”,它们用于本机资源,如窗口句柄。资源的大小取决于使用的硬件和操作系统,但其大小总是足以包含系统的指针(因此也可以包含资源的名称)。



说明: 
  1、DllImport只能放置在方法声明上。 
  2、DllImport具有单个定位参数:指定包含被导入方法的 dll 名称的 dllName 参数。 
  3、DllImport具有五个命名参数: 
   a、CallingConvention 参数指示入口点的调用约定。如果未指定 CallingConvention,则使用默认值 CallingConvention.Winapi。 
   b、CharSet 参数指示用在入口点中的字符集。如果未指定 CharSet,则使用默认值 CharSet.Auto。 
   c、EntryPoint 参数给出 dll 中入口点的名称。如果未指定 EntryPoint,则使用方法本身的名称。 
   d、ExactSpelling 参数指示 EntryPoint 是否必须与指示的入口点的拼写完全匹配。如果未指定 ExactSpelling,则使用默认值 false。 
   e、PreserveSig 参数指示方法的签名应当被保留还是被转换。当签名被转换时,它被转换为一个具有 HRESULT 返回值和该返回值的一个名为 retval 的附加输出参数的签名。如果未指定 PreserveSig,则使用默认值 true。 
   f、SetLastError 参数指示方法是否保留 Win32"上一错误"。如果未指定 SetLastError,则使用默认值 false。 
  4、它是一次性属性类。 
  5、此外,用 DllImport 属性修饰的方法必须具有 extern 修饰符。



调用c库的时候,多次调用会导致程序崩溃,原因是内存存在泄漏。



调用代码

  

  public static string testDll(string paramString)
    {
            IntPtr param = Marshal.StringToHGlobalAnsi(paramString);  
            IntPtr tokenId = Marshal.StringToHGlobalAnsi("1231313122121");
             // 分配返回值的指针空间 10240,需要根据返回值的大小进行调整,如果长度小于返回值也会出现崩溃
            IntPtr retMessage = mallocIntptr(10240); 
            int retLen = 0;
            try
            {
                int result = test(param, tokenId, retMessage, ref retLen);
               Console.writeLine(Marshal.PtrToStringAnsi(retMessage)) ; 
            }
            finally
            {
                Marshal.FreeHGlobal(retMessage); // 释放分配的内存空间。 
            }
        }
       /// <summary>  
       /// 根据长度申请非托管空间  
       /// </summary>  
       /// <param name="strData">要申请非托管空间的大小</param>  
       /// <returns>指向非拖管空间的指针</returns>  
       internal static IntPtr mallocIntptr(int length)
       {
           IntPtr m_ptr = Marshal.AllocHGlobal(length);
           Byte[] btZero = new Byte[length + 1]; //一定要加1,否则后面是乱码  
           Marshal.Copy(btZero, 0, m_ptr, length); //给指针指向的空间赋值  
           return m_ptr;
       }



注:

1 IntPtr Marshal.AllocHGlobal(int), 使用Marshal.FreeHGlobal(IntPtr)释放
2 IntPtr Marshal.AllocCoTaskMem(int), 使用Marshal.FreeCoTaskMem(IntPtr)释放




转载于:https://my.oschina.net/heavenick/blog/489068

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值