使用 Python 访问 C# dll 中存在的函数
Access a function present in C# dll using Python
我想访问函数 my_function() 存在于编译成 .net dll 的 c# 文件中 - 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
使用下面的 python 尝试访问 my_function()
import ctypes
lib = ctypes.WinDLL('abc.dll')
print lib.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 中可见。
有几种不同的方法可以做到这一点。最简单的可能是使用 unmanagedexports 包。它允许您通过使用 [DllExport] 属性装饰函数来像普通 C 函数一样直接调用 C# 函数,例如 P/Invoke 的 DllImport。它使用部分子系统来使 C++/CLI 混合托管库工作。
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)
我想访问函数 my_function() 存在于编译成 .net dll 的 c# 文件中 - 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
使用下面的 python 尝试访问 my_function()
import ctypes
lib = ctypes.WinDLL('abc.dll')
print lib.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 中可见。
有几种不同的方法可以做到这一点。最简单的可能是使用 unmanagedexports 包。它允许您通过使用 [DllExport] 属性装饰函数来像普通 C 函数一样直接调用 C# 函数,例如 P/Invoke 的 DllImport。它使用部分子系统来使 C++/CLI 混合托管库工作。
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)