python、c# 调用动态链接库DLL,输入参数并获取返回值

您所在的位置:网站首页 python调用c++库获取返回值 python、c# 调用动态链接库DLL,输入参数并获取返回值

python、c# 调用动态链接库DLL,输入参数并获取返回值

2024-07-05 02:29| 来源: 网络整理| 查看: 265

因为我用到的dll动态库是32位的,所以安装的python环境对应的也必须是32位才可以调用

dll函数说明:

python代码: import ctypes import platform print(platform.architecture()) dll_path = r"C:\Users\Administrator\Desktop\sbk\SSCardDriver.dll" # 加载动态链接库 sscard_driver = ctypes.windll.LoadLibrary(dll_path) # 定义函数参数类型 sscard_driver.iReadCardBas.argtypes = [ctypes.c_int, ctypes.c_char_p] # 定义函数返回值类型 sscard_driver.iReadCardBas.restype = ctypes.c_long # 调用函数 iType = 3 pOutInfo = ctypes.create_string_buffer(1024) # 输出信息的最大长度是,具体看接口定义多少 result = sscard_driver.iReadCardBas(iType, pOutInfo) # 处理返回值和输出信息 print(f"函数返回代码: {result}") print(f"函数返回信息: {pOutInfo.value}") print(f"函数返回信息: {pOutInfo.value.decode('gbk')}")

代码中 platform.architecture() 打印当前环境是32位还是64位 本次使用的dll动态库是32位的,如果环境是64位的会报错,C#也是一样的,运行平台选择X86

c#代码调用如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace xxx.sbk { public class Program { // 拷贝SSCardDriver.dll到bin\x86\Debug\net8.0目录下, 运行平台选择X86 [DllImport("SSCardDriver.dll", CallingConvention = CallingConvention.Cdecl)] public static extern long iReadCardBas(int iType, IntPtr pOutInfo); static void Main() { const int bufferSize = 1024; // 整缓冲区大小 IntPtr buffer = Marshal.AllocHGlobal(bufferSize); try { int iType = 3; // 1-接触式操作卡;2-非接触式操作卡;3 - 自动寻卡,接触式操作卡优先;4 - 自动寻卡,非接触式操作卡优先 Console.WriteLine($"开始调用 SSCardDriver.dll | 方法名称: iReadCardBas | 参数iType: {iType}"); long result = iReadCardBas(iType, buffer); // 将结果从指针中复制到字符串 string outInfo = Marshal.PtrToStringAnsi(buffer); // 处理结果 Console.WriteLine("iReadCardBas返回代码: " + result); Console.WriteLine("iReadCardBas返回信息: " + outInfo); } finally { // 释放分配的缓冲区 Marshal.FreeHGlobal(buffer); } } } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3