【问题标题】:How to import a C# dll to python如何将 C# dll 导入 python
【发布时间】:2016-01-22 00:14:01
【问题描述】:

我有一个第三方 c# dll,它是在 dot net 4.5 中创建的,平台目标是 x86。我想将其导入 python 脚本,并从 Rob Deary 的回答 here 开始。但是我无法让他的例子起作用。我使用的是 python 版本 2.7.6,我得到一个 AttributeError 如下所示。

File "C:\Python27\Lib\ctypes\__init__.py", line 378, in __getattr__
    func = self.__getitem__(name)
File "C:\Python27\Lib\ctypes\__init__.py", line 383, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'add' not found

请注意,我知道 Ironpython 和 Python 用于 dot net,但我需要专门使用 C python。这是我生成自定义 c# 库的示例代码:ClassLibrary1.dll

using System;
using System.Runtime.InteropServices;
using RGiesecke.DllExport;

class Test
{
    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
    public static int TestExport(int a, int b)
    {
        return a + b;
    }
}

这是产生错误的python脚本

import ctypes
lib = ctypes.cdll.LoadLibrary('ClassLibrary1.dll')
lib.add(3,5)

当我使用下面的行时,这是我得到的输出。所以至少我知道它正在加载 dll,但我不确定为什么找不到该函数。

>>> lib.__dict__
{'_FuncPtr': <class 'ctypes._FuncPtr'>, '_handle': 254476288, '_name': 'ClassLibrary1.dll'}
>>>

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 您将 python 类型而不是 c_types 传递给使用 ctypes 在 python 中加载的 lib 函数。试试lib.add(c_int(3),c_int(5))

标签: c# python .net dll attributeerror


【解决方案1】:

作为rgiesecke.dlexport文档状态,您需要在构建代码时定位特定架构(x86或x64)。将其设置为 Any CPU(默认值)将不起作用。

【讨论】:

  • 如果您重新阅读我的问题,您会发现平台目标已指定为 x86
  • 你提到第三方 DLL 是为 x86 编译的,但如果你自己的代码是这样的话。是第三方DLL也使用dllexport属性吗?我想我只是困惑了为什么你开始谈论第三方DLL,但然后显示你自己的代码根本没有使用该DLL。您的代码是正确的,应该工作,所以它必须是您未显示的东西。 span>
猜你喜欢
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-12
相关资源
最近更新 更多