Python import dll

后端 未结 4 1722
灰色年华
灰色年华 2020-12-03 14:35

How would I import a winDLL into python and be able to use all of its functions? It only needs doubles and strings.

4条回答
  •  感动是毒
    2020-12-03 14:53

    I'm posting my experience. First of all despite all the hard work that take me to put all pieces together, importing a C# dll is easy. The way I did it is:

    1) Install this nuget package (i'm not owner, is just very useful) in order to build a unmanaged dll: https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports

    2) Your C# dll code is like this:

    using System;
    using RGiesecke.DllExport;
    using System.Runtime.InteropServices;
    
    public class MyClassName
    {
       [DllExport("MyFunctionName",CallingConvention = CallingConvention.Cdecl)]
       [return: MarshalAs(UnmanagedType.LPWStr)]
       public static string MyFunctionName([MarshalAs(UnmanagedType.LPWStr)] string iString)
       {
           return "hello world i'm " + iString
       }
    }
    

    3) Your python code is like this:

    import ctypes
    #Here you load the dll into python 
    MyDllObject = ctypes.cdll.LoadLibrary("C:\\My\\Path\\To\\MyDLL.dll")
    #it's important to assing the function to an object
    MyFunctionObject = MyDllObject.MyFunctionName
    #define the types that your C# function return
    MyFunctionObject.restype = ctypes.c_wchar_p
    #define the types that your C# function will use as arguments
    MyFunctionObject.argtypes = [ctypes.c_wchar_p]
    #That's it now you can test it
    print(MyFunctionObject("Python Message"))
    

提交回复
热议问题