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

怎甘沉沦 提交于 2019-11-29 02:03:42
gurney alex

The tips you'll find regarding calling DLL from Python using ctypes rely most of the time to the DLL being written in C or C++, not C#. With C# you pull in the whole machinery of the CLR, and the symbols are most likely mangled and not what ctypes expect, and you'll get all sorts of troubles from the garbage collection of your output array.

I've had very good success when interfacing python and C# code by using python for dot net (http://pythonnet.sf.net), you may want to try this.

On the other hand if you are in for pure performance, consider rewriting your code as a native C extension for Python using the Python/C API (http://docs.python.org/c-api/).

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)

Others have pointed out that a C# DLL cannot be treated the same way as a native DLL.

One option you have is to export your C# functionality as a COM object which can be readily consumed by Python.

Personally I'd consider a native code solution but you may well be too committed to C# to change course at this stage.

ctypes is for loading shared libraries written in C (or at least shared libraries that are directly executable by the CPU and export their symbols and function arguments following the standard C conventions.) C# DLLs are not "normal" DLLs, but rather intended to run in a .NET environment.

Your options are:

  1. Use some sort of Python to .NET bridge.
  2. Write the DLL in C and use ctypes to call the function and handle the data conversions.
  3. Use the Python/C API and create a loadable Python module.

I can't speak to option #1, I have not done it. Option #2 is typically easier than option #3 in that you write pure C code and glue it in with ctypes. Option #3 will offer the best performance of all three options in that it has the lowest call overhead and is running native code on the processor.

A C# DLL is really referred to as an Assembly so it is quite different. Unless there is a very important reason I suggest you use C++

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!