美文网首页
C#调用dll 返回char *类型时

C#调用dll 返回char *类型时

作者: 修玛哦 | 来源:发表于2018-08-01 15:38 被阅读0次
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Runtime.InteropServices;
    
    namespace ConsoleApp3
    {
        class Program
        {
            [DllImport(@"C:\Users\cj\source\repos\ConsoleApp3\ConsoleApp3\BDK01ForCryptolDll.dll")]
            public static extern bool OpenBDK01();
            [DllImport(@"C:\Users\cj\source\repos\ConsoleApp3\ConsoleApp3\BDK01ForCryptolDll.dll")]
            public static extern bool CloseBDK01();
            [DllImport(@"C:\Users\cj\source\repos\ConsoleApp3\ConsoleApp3\BDK01ForCryptolDll.dll")]
            public static extern int GetMyPinCount();
            [DllImport(@"C:\Users\cj\source\repos\ConsoleApp3\ConsoleApp3\BDK01ForCryptolDll.dll")]
            public static extern IntPtr GetDevSN();
            [DllImport(@"C:\Users\cj\source\repos\ConsoleApp3\ConsoleApp3\BDK01ForCryptolDll.dll")]
            public static extern char LoginForBDK01(Byte[] lpPassword, int iPWLen);
            [DllImport(@"C:\Users\cj\source\repos\ConsoleApp3\ConsoleApp3\BDK01ForCryptolDll.dll")]
            public static extern char EncryptForSM4(byte[] lpEData, byte[] lpDData, int iDLen);
            [DllImport(@"C:\Users\cj\source\repos\ConsoleApp3\ConsoleApp3\BDK01ForCryptolDll.dll")]
            public static extern char DecyptForSM4(byte[] lpDData, byte[] lpEData, int iDLen);
            static void Main(string[] args)
            {
                bool Device_status = OpenBDK01();
                string devsn = Marshal.PtrToStringAnsi(GetDevSN());
    
                while (true)
                {
                    Console.WriteLine("the device SN is {0}", devsn);
                    Console.WriteLine("the device status is {0}", Device_status);
    
                }
            }
        }
    }
    

    一、IntPtr 与 string互转

    string str = "aa";

    IntPtr init = Marshal.StringToHGlobalAnsi(str);

    string ss= Marshal.PtrToStringAnsi(init);

    //最后释放掉

    Marshal.FreeHGlobal(init);

    二、char*与string互转

    string a = "11";

    char* aChar = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(a).ToPointer();

    string result = Marshal.PtrToStringAnsi((IntPtr)aChar);

    三、char* 与 IntPtr互转

    可以直接强制类型转换

    IntPtr init = (IntPtr)aChar;

    char* aChar = (char*)init;

    相关文章

      网友评论

          本文标题:C#调用dll 返回char *类型时

          本文链接:https://www.haomeiwen.com/subject/hqlrvftx.html