使用Python访问C#dll中存在的函数 [英] Access a function present in C# dll using Python
问题描述
我想访问存在于c#文件中的函数 my_function(),该函数已编译为.net dll- abc.dll .
I want to access a function my_function() present in a c# file which is compiled into a .net dll - abc.dll.
C#文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class Class1
{
public string my_function()
{
return "Hello World.. :-";
}
}
}
将上面的代码编译为abc.dll后
After compiling the above code to abc.dll
使用下面的python尝试访问my_function()
import ctypes
lib = ctypes.WinDLL('abc.dll')
print lib.my_function()
以上代码会引发错误
lib.my_function()追溯(最近一次通话):文件",第1行,在 getattr 中的文件"C:\ Anaconda \ lib \ ctypes__init __.py",行378func = self.获取项(名称) getitem 中的文件"C:\ Anaconda \ lib \ ctypes__init __.py",第383行func = self._FuncPtr((name_or_ordinal,self))AttributeError:找不到函数"my_function"
lib.my_function() Traceback (most recent call last): File "", line 1, in File "C:\Anaconda\lib\ctypes__init__.py", line 378, in getattr func = self.getitem(name) File "C:\Anaconda\lib\ctypes__init__.py", line 383, in getitem func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'my_function' not found
推荐答案
您尚未使该函数在DLL中可见.
You haven't made the function visible in the DLL.
有几种不同的方法可以执行此操作.最简单的方法可能是使用 unmanagedexports 程序包.它允许您通过使用[DllExport]属性装饰函数(例如P/Invoke的DllImport)来直接调用C#函数,就像调用普通C函数一样.它使用了子系统的一部分,旨在使C ++/CLI混合托管库正常工作.
There are a few different ways you can do this. The easiest is probably to use the unmanagedexports package. It allows you to call C# functions directly like normal C functions by decorating your function with [DllExport] attribute, like P/Invoke's DllImport. It uses part of the subsystem meant to make C++/CLI mixed managed libraries work.
C#代码
class Example
{
[DllExport("ExampleFunction", CallingConvention = CallingConvention.StdCall)]
public static int ExampleFunction(int a, int b)
{
return a + b;
}
}
Python
import ctypes
lib = ctypes.WinDLL('example.dll')
print lib.ExampleFunction(12, 34)
这篇关于使用Python访问C#dll中存在的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!