通过COM,用Python调用C#库

1.C#配置
(1)类库

(2)COM互操作打勾

(3)代码中类必须要有无参构造函数,否则不会注册成功!!!

using System;
using System.Runtime.InteropServices;

namespace MyLibrary
{
    

    [ComVisible(true)] // 确保类和成员在COM互操作中可见
    [Guid("12345678-1234-1234-1234-1234567890AB")] // 用于标识COM组件的GUID
    public class MyComponent
    {
        public string GetMessage()
        {
            return "Hello from C#!";
        }

        public int AddNumbers(int a, int b)
        {
            return a + b;
        }
        public Point AddPoints(Point a,Point b)
        {
            Point p = new Point();
            p.x = a.x + b.x;
            p.y = a.y + b.y;
            return p;
        }
    }

    [ComVisible(true)]
    [Guid("B479D2EB-F2D5-4EC9-B83B-CB007966E0B0")]
    public class Point
    {
        public int x;
        public int y;

    }
    [ComVisible(true)]
    [Guid("B481D2EB-F2D5-4EC9-B83B-CB007966E0B0")]
    public class Testtt
    {

    }
    [ComVisible(true)]
    [Guid("B461D2EB-F2D5-4EC9-B83B-CB007966E0B0")]
    public class Point2
    {

        public int x;

        public int y;
        public Point2()//必须要有无参构造函数
        {

        }
        public Point2(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }
    [ComVisible(true)]
    [Guid("B451D2EB-F2D5-4EC9-B83B-CB007966E0B0")]
    public class Point3//注册失败,因为没有无参构造函数
    {

        public int x;

        public int y;

        public Point3(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }
}


(4)用管理员的方式对类库重生成!
(5)在注册表中查看,以上类是否注册成功,win+R,regedit,导航到以下路径HKEY_CLASSES_ROOT\CLSID:

可以发现,正好是C#代码中的GUID。
(6)python代码:

发现调用成功。
(7)拷贝到其他电脑上需要做的事:
注册COM组件:在目标电脑上,使用regsvr32命令注册COM组件。打开命令提示符或PowerShell,并执行以下命令:
regsvr32 path\to\MyLibrary.dll
其中,path\to\MyLibrary.dll是你在目标电脑上放置MyLibrary.dll文件的路径。这将确保COM组件在目标电脑上正确注册。
需要注意的是,如果目标电脑的操作系统架构与你开发时使用的不同(例如,32位与64位之间的转换),则还需要确保使用相应架构的组件和设置。

posted @ 2023-05-16 22:42  JohnYang819  阅读(228)  评论(0编辑  收藏  举报