任何人都可以分享一个关于如何从 python 代码调用简单的 C# 库(实际上是它的 WPF)的工作示例? (我尝试过使用 IronPython 并且在我的 python 代码正在使用的不受支持的 CPython 库上遇到了太多麻烦,所以我想尝试另一种方式并从 Python 调用我的 C# 代码)。
这是我正在玩的示例:
using System.Runtime.InteropServices;
using System.EnterpriseServices;
namespace DataViewerLibrary
{
public interface ISimpleProvider
{
[DispIdAttribute(0)]
void Start();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class PlotData : ServicedComponent, ISimpleProvider
{
public void Start()
{
Plot plotter = new Plot();
plotter.ShowDialog();
}
}
}
Plotter 是一个绘制椭圆的 WPF 窗口
我不知道如何从我的 python 中调用这段代码。有什么建议么?
最佳答案
其实很简单。只需使用 NuGet 将“UnmanagedExports”包添加到您的 .Net 项目。见 https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports了解详情。
然后您可以直接导出,而无需执行 COM 层。这是示例 C# 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using RGiesecke.DllExport;
class Test
{
[DllExport("add", CallingConvention = CallingConvention.Cdecl)]
public static int TestExport(int left, int right)
{
return left + right;
}
}
然后您可以加载 dll 并在 Python 中调用公开的方法(适用于 2.7)
import ctypes
a = ctypes.cdll.LoadLibrary(source)
a.add(3, 5)
关于c# - 从 python 调用 C# 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7367976/