python调用.net的dll使用pythonnet,在pypi上面看到python3.5-3.8支持pythonnet,3.9环境中有错误提示。
都是网上示例:
TestPython.Core
using System;
namespace TestPython.Core
{
public class Man
{
public string Name { get; set; }
public Man()
{
}
public Man(string name)
{
Name = name;
}
public int Add(int a, int b)
{
return a + b;
}
public string Say(string msg)
{
var fullMsg = $"{Name} Say: {msg}";
Console.WriteLine(fullMsg);
return fullMsg;
}
}
}
import clr
clr.AddReference("TestPython.Core")
print("OK")
from TestPython.Core import *
m = Man()
msg=m.Say("hi,big man!")
input("press enter to exit...")
TestDll
using System;
namespace TestDll
{
public class MyTest
{
public void Print()
{
Console.WriteLine("Hello world!!!");
}
public void Print(string msg)
{
Console.WriteLine($"Hello {msg}!!!");
}
public double Add(double x, double y)
{
return x + y;
}
}
}
# coding:utf-8
import clr
# 引用Dll,不需要添加后缀
clr.AddReference("TestDll")
# TestDll是命名空间,MyTest是命名空间里定义的类
from TestDll import MyTest
# 实例化类
instance = MyTest()
# 无输入及无返回
instance.Print()
# 有输入及无返回
instance.Print("qin")
# 有输入及输出
add_data = instance.Add(1, 1)
print(add_data)