我想在我的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项目中的“Build”命令,该项目仅包含此文件和对“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”类的情况下直接访问该函数时,它仍然会抛出异常... 我不知道问题可能出在哪里。