如何将C#dll导入python

时间:2015-10-22 16:17:17

标签: c# python .net dll attributeerror

我有一个第三方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

请注意,我知道Ironpy和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'}
>>>

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

1 个答案:

答案 0 :(得分:0)

正如RGiesecke.DllExport文档所述,您需要在构建代码时定位特定的体系结构(x86或x64)。将其设置为Any CPU(默认值)将不起作用。