从python调用C库

2024-06-16 10:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

任何人都可以分享一个关于如何从python代码中调用一个简单的C#库(实际上是它的WPF)的工作示例?(我试过使用IronPython,但是在使用不受支持的C python库时遇到了太多的问题,所以我想换一种方式,从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();
       }
    }
}

绘图仪是绘制椭圆的WPF窗口

我不知道如何从我的python all调用这段代码。有什么建议吗?


Tags: 代码示例plot方式publicsystemstart例子
3条回答

由于您的文章被标记为IronPython,如果您想使用示例C#以下应该可以工作。

import clr
clr.AddReference('assembly name here')
from DataViewerLibrary import PlotData 

p = PlotData()
p.Start()

其实很简单。只需使用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)

在您的情况下,Python for .Net (pythonnet)可能是IronPython的合理替代方案。 https://github.com/pythonnet/pythonnet/blob/master/README.rst

从站点:

Note that this package does not implement Python as a first-class CLR language - it does not produce managed code (IL) from Python code. Rather, it is an integration of the CPython engine with the .NET runtime. This approach allows you to use use CLR services and continue to use existing Python code and C-based extensions while maintaining native execution speeds for Python code.

同时

Python for .NET uses the PYTHONPATH (sys.path) to look for assemblies to load, in addition to the usual application base and the GAC. To ensure that you can implicitly import an assembly, put the directory containing the assembly in sys.path.

这个包仍然要求您的计算机上有一个本地的CPython运行时。 有关详细信息,请参阅完整的自述文件http://pythonnet.github.io/readme.html

相关问题 更多 >