Using ctypes in python to access a C# dll's methods

前端 未结 5 2191
生来不讨喜
生来不讨喜 2020-12-16 02:48

I would like to implement C# code in a critical part of my python program to make it faster. It says (on Python documentation and this site) that you can load a Dynamic Link

5条回答
  •  青春惊慌失措
    2020-12-16 03:12

    It is actually pretty easy. Just use NuGet to add the "UnmanagedExports" package to your .Net project. See https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports for details.

    You can then export directly, without having to do a COM layer. Here is the sample C# code:

    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;
        }
    }
    

    You can then load the dll and call the exposed methods in Python (works for 2.7)

    import ctypes
    a = ctypes.cdll.LoadLibrary(source)
    a.add(3, 5)
    

提交回复
热议问题