简体   繁体   English

如何将C#dll导入python

[英]How to import a C# dll to python

i've got a third party c# dll which has been created in dot net 4.5 and has a platform target of x86. 我有一个第三方c#dll,它是在dot net 4.5中创建的,其平台目标是x86。 I would like to import this into a python script and I've started off with Rob Deary's answer here . 我想将它导入到python脚本中,我已经开始使用Rob Deary的答案 However I can't get his example to work. 但是,我无法让他的榜样奏效。 I'm using python version 2.7.6 and I get an AttributeError as shown below. 我正在使用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

Please note that I am aware of Ironpython and Python for dot net but I need to get this working specifically with C python. 请注意,我知道使用Ironpy和Python for dot net,但我需要专门用C python进行这项工作。 Here's my sample code which generates the custom c# library: ClassLibrary1.dll 这是我生成自定义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;
    }
}

And here's the python script that generates the error 这是生成错误的python脚本

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

When I use the line below, this is the output i get. 当我使用下面的行时,这是我得到的输出。 So at least I know that it is loading the dll, but i'm not sure why the function can't be found. 所以至少我知道它正在加载dll,但我不确定为什么无法找到该函数。

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

Any help will be appreciated. 任何帮助将不胜感激。 Thanks 谢谢

As the RGiesecke.DllExport documentation states, you need to target a specific architecture (x86 or x64) when building your code. 正如RGiesecke.DllExport文档所述,您需要在构建代码时针对特定体系结构(x86或x64)。 Leaving it set to Any CPU (the default) will not work. 将其设置为任何CPU(默认值)将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM