【问题标题】:Access a function present in C# dll using Python使用 Python 访问 C# dll 中存在的函数
【发布时间】:2016-11-28 21:07:31
【问题描述】:

我想访问一个存在于 c# 文件中的函数 my_function(),该文件被编译为 .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后

使用下面的 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”,第 378 行 func = self.getitem(名称) getitem 中的文件“C:\Anaconda\lib\ctypes__init__.py”,第 383 行 func = self._FuncPtr((name_or_ordinal, self)) AttributeError:找不到函数“my_function”

【问题讨论】:

  • 我猜你应该使用完整函数的命名空间。你试过print lib.Test.Class1.my_function() 吗?
  • 你必须让你的 .net dll COM 可见。

标签: c# python .net ctypes dllimport


【解决方案1】:

您尚未使该函数在 DLL 中可见。

有几种不同的方法可以做到这一点。最简单的可能是使用unmanagedexports 包。它允许您通过使用 [DllExport] 属性(如 P/Invoke 的 DllImport)装饰您的函数来像普通 C 函数一样直接调用 C# 函数。它使用了部分子系统,旨在使 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)

【讨论】:

  • 我是否需要为此包含和命名空间,因为即使在包含 DLLExport 包后出现错误 - 找不到类型或命名空间名称“DLLExport”。
  • 您需要从我链接的网站安装 Unmanaged Exports 包,或者在“项目”下找到 NuGet 包,然后在“管理 NuGet 包...”中安装。
  • 它仍然显示相同的错误 - AttributeError: function 'ExampleFunction' not found
  • 那你做错了什么。但现在这是你要调试的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
相关资源
最近更新 更多