在python中使用ctypes访问C#dll的方法
我想在我的python程序的关键部分实现C#代码,以使其更快。它说(在Python文档和此站点上),您可以按以下方式加载动态链接库(也就是PyDocs):
cdll.LoadLibrary("your-dll-goes-here.dll")
这是我的代码中负责此功能的部分:
from ctypes import *
z = [0.0,0.0]
c = [LEFT+x*(RIGHT-LEFT)/self.size, UP+y*(DOWN-UP)/self.size]
M = 2.0
iterator = cdll.LoadLibrary("RECERCATOOLS.dll")
array_result = iterator.Program.ITERATE(z[0],z[1],c[0],c[1],self.iterations,M)
z = complex(array_result[0],array_result[1])
c = complex(array_result[2],array_result[3])
last_iteration = int(round(array_result[4]))
我使用的RECERCATOOLS.dll是这样的(C#代码,而不是C或C ++):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KarlsTools;
public class Program
{
public static Array ITERATE(double z_r,double z_i,double c_r,
double c_i, int iterations,
double limit)
{
Complex z = new Complex(z_r, z_i);
Complex c = new Complex(c_r, c_i);
for (double i = 1; Math.Round(i) <= iterations; i++)
{
z = Complex.Pow(z, 2) + c;
if (Complex.Abs(z) < limit)
{
double[] numbers = new double[] { Complex.Real(z),
Complex.Imag(z),
Complex.Real(c),
Complex.Imag(c),
i};
return numbers;
}
}
double iter = iterations;
double[] result = new double[] { Complex.Real(z),
Complex.Imag(z),
Complex.Real(c),
Complex.Imag(c),
iter};
return result;
}
}
要构建此DLL,我在Visual Studio 2010项目上使用“构建”命令,该项目仅包含此文件和对“
Karlstools”的引用,该模块允许我使用复数。
我不知道为什么,但是当我尝试运行我的Python代码时,它只会引发异常:
[...]
array_result = iterator.Program.ITERATE(z[0],z[1],c[0],c[1],self.iterations,M)
File "C:\Python32\lib\ctypes\__init__.py", line 353, in __getattr__
func = self.__getitem__(name)
File "C:\Python32\lib\ctypes\__init__.py", line 358, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'Program' not found
我需要这方面的帮助,因为即使将所有内容都设置为,public
并且将函数设置为static
,或者即使我尝试不指定“
Program”类直接访问该函数,它也会不断抛出异常…我不知道该在哪里问题可能是。
-
您会发现有关使用ctypes从Python调用DLL的技巧大部分时间依赖于用C或C
++而不是C#编写的DLL。使用C#,您需要拉入CLR的整个机制,并且符号很可能被弄乱了,而不是ctypes所期望的那样,并且您将在输出数组的垃圾回收中遇到各种麻烦。当使用python的点网(http://pythonnet.sf.net)连接python和C#代码时,我取得了很好的成功,您可能想尝试一下。
另一方面,如果您追求纯粹的性能,请考虑使用Python / C
API(http://docs.python.org/c-api/)将代码重写为Python的本机C扩展。