我以前从不需要在 C# 中使用指针,但是,我使用的库要求方法参数作为指针传递。该库允许使用 SIMD 指令集。
为了测试如何使用该库,我尝试编写一种使用 SIMD 一次性计算数组所有元素的余弦值的方法。
这是我得到的:
double[] ValuesToCalculate = new double[MAX_SIZE];
double[] CalculatedCosines = new double[MAX_SIZE];
long Result;
Result = CalculateCosineArray(ValuesToCalculate, CalculatedCosines);
public static long CalculateCosineArraySIMD(double[] array, double[] result)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < array.Length; i++)
{
Yeppp.Math.Cos_V64f_V64f(*array, result, MAX_SIZE);
}
stopwatch.Stop();
return stopwatch.ElapsedMilliseconds;
}
但是,我得到了这些错误:
The best overloaded method match for 'Yeppp.Math.Cos_V64f_V64f(double*, double*, int)' has some invalid arguments
Argument 1: cannot convert from 'double[]' to 'double*'
The * or -> operator must be applied to a pointer
Argument 2: cannot convert from 'double[]' to 'double*'
如何让指针在这段代码中工作?同样,这是我在使用 C# 期间第一次出现指针。
最佳答案
您必须使用fixed
语句从数组中获取指针。
大概是这样的:
public static long CalculateCosineArraySIMD(double[] array, double[] result)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
fixed (double* arrayPtr = array, resultPtr = result)
{
Yeppp.Math.Cos_V64f_V64f(arrayPtr, resultPtr, MAX_SIZE);
};
stopwatch.Stop();
return stopwatch.ElapsedMilliseconds;
}
关于c# - 试图让指针工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21592332/