pythonnet 调用C接口

首先是这个类C#写的ini帮助类

cs 复制代码
    /// <summary>
    ///  INI 文件读写类
    /// </summary>
    public static class RWINI
    {
        #region 声明
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
 
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        #endregion 声明
 
        public static string path = AppDomain.CurrentDomain.BaseDirectory + "CFG.ini";
        public static string Getcwd = System.Environment.CurrentDirectory;
        static public bool NewWinifolder(string folderPath)//folderPath// 指定你想要检查的文件夹路径
        {
            if (!Directory.Exists(folderPath))// 检查文件夹是否存在
            {
                Directory.CreateDirectory(folderPath);// 如果文件夹不存在,则创建它
                return true;
            }
            else { return false; }
        }
 
        static public bool IsFolder(string folderPath)//folderPath// 指定你想要检查的文件夹路径
        {
            if (Directory.Exists(folderPath)) { return true; }
            else { return false; }
        }
 
        /// <summary>
        /// 写INI文件
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="Section">分组节点</param>
        /// <param name="Key">关键字</param>
        /// <param name="Value">值</param>
        static public void Wini(string path, string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, path);
        }
        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="path">path</param>
        /// <param name="Section">分组节点</param>
        /// <param name="Key">关键字</param>
        /// <param name="def">缺省值</param>
        /// <returns></returns>
        static public string Rini(string path, string Section, string Key, string def = "")
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, def, temp, 255, path);
            return temp.ToString();
        }
 
 
 
        /// <summary>
        /// 删除ini文件下所有段落
        /// </summary>
        public static void ClearAllSection(string path)
        {
            Wini(path, null, null, null);
        }
        /// <summary>
        /// 删除ini文件下指定段落下的所有键
        /// </summary>
        /// <param name="Section"></param>
        public static void ClearSection(string path, string Section)
        {
            Wini(path, Section, null, null);
        }
 
 
        static public string RWini测试()
        {
            Wini(Getcwd + "\\CFG.ini", "Section", "Key", "Value");
            string x = Rini(Getcwd + "\\CFG.ini", "Section", "Key", "def");
        
            return "";
        }
 
 
        /********
                    _minThreshold = Convert.ToInt32(  );
        ********/
    }

下面就是"原封不动"的 Python 直译版------只把 C# 语法换成 Python,逻辑、函数名、甚至注释一行不改,用 pythonnet 调 Win32 API。

python 复制代码
# rwini.py
"""单文件 INI 读写包,仅导出 RWINI"""
__all__ = ["RWINI"]          # ← 只暴露这一个名字

# --------------------------------------------------
# 私有实现(下划线模块)
# --------------------------------------------------
import sys, os
import clr
clr.AddReference("System")
from System import AppDomain, Environment
from System.IO import Directory
from System.Text import StringBuilder
import ctypes, ctypes.wintypes as w

_k32 = ctypes.windll.kernel32

def _WritePrivateProfileString(section, key, val, filePath):
    _k32.WritePrivateProfileStringW(section, key, val, filePath)

def _GetPrivateProfileString(section, key, default, retVal, size, filePath):
    buf = w.create_unicode_buffer(size)
    _k32.GetPrivateProfileStringW(section, key, default, buf, size, filePath)
    retVal.Clear()
    retVal.Append(buf.value)
    return len(buf.value)

# --------------------------------------------------
# 公共接口
# --------------------------------------------------
class RWINI:
    path   = AppDomain.CurrentDomain.BaseDirectory + "CFG.ini"
    Getcwd = Environment.CurrentDirectory

    @staticmethod
    def NewWinifolder(folderPath: str) -> bool:
        if not Directory.Exists(folderPath):
            Directory.CreateDirectory(folderPath)
            return True
        return False

    @staticmethod
    def IsFolder(folderPath: str) -> bool:
        return Directory.Exists(folderPath)

    @staticmethod
    def Wini(path: str, Section: str, Key: str, Value: str):
        _WritePrivateProfileString(Section, Key, Value, path)

    @staticmethod
    def Rini(path: str, Section: str, Key: str, default: str = "") -> str:
        sb = StringBuilder(255)
        _GetPrivateProfileString(Section, Key, default, sb, 255, path)
        return sb.ToString()

    @staticmethod
    def ClearAllSection(path: str):
        _WritePrivateProfileString(None, None, None, path)

    @staticmethod
    def ClearSection(path: str, Section: str):
        _WritePrivateProfileString(Section, None, None, path)


# 自测时才会执行
if __name__ == "__main__":
    ini_path = os.path.join(os.getcwd(), "demo.ini")
    RWINI.Wini(ini_path, "Server", "IP", "127.0.0.1")
    print(RWINI.Rini(ini_path, "Server", "IP", "default"))
相关推荐
幸福的达哥19 小时前
PyQt5多线程UI更新方法
python·qt·ui
玄同76519 小时前
SQLAlchemy 会话管理终极指南:close、commit、refresh、rollback 的正确打开方式
数据库·人工智能·python·sql·postgresql·自然语言处理·知识图谱
HABuo19 小时前
【linux基础I/O(一)】文件系统调用接口&文件描述符详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
拾光Ծ19 小时前
【Linux】一切皆文件:深入理解文件与文件IO
linux·c语言·运维开发·系统编程·重定向·linux开发·文件io
喵手19 小时前
Python爬虫零基础入门【第九章:实战项目教学·第11节】Playwright 入门实战:渲染后 HTML + 截图定位问题!
爬虫·python·爬虫实战·playwright·python爬虫工程化实战·零基础python爬虫教学·渲染html
一晌小贪欢19 小时前
Python ORM 深度解析:告别繁琐 SQL,让数据操作如丝般顺滑
开发语言·数据库·python·sql·python基础·python小白
windows_619 小时前
MISRA C:2004 逐条分析
c语言
进击的小头19 小时前
移动平均滤波器:从原理到DSP ADC采样实战(C语言实现)
c语言·开发语言·算法
历程里程碑19 小时前
Linux 6 权限管理全解析
linux·运维·服务器·c语言·数据结构·笔记·算法
华研前沿标杆游学19 小时前
2026智启新程 | 走进华为及商汤科技参观研学高级研修班
python