从C#将数组传递给函数指针

时间:2018-09-22 01:30:58

标签: c# unmanaged

我已经在C程序中实现了一些功能,并将其包装到一个dll中,该dll将在另一个C#项目中调用。 dll中的函数之一将函数指针作为输入参数,即,在生成dll的源代码中,其中一个函数如下所示:

void functionA(
    int* a,
    int* b,
    double *c,
    double[] inputArr,
    double[] outputtArr,
    void(*fun)(int*, int*,double[],double[])
)

在functionA内,inputArr将用作函数指针的输入,而outputArr将用作输出。 inputArr的尺寸应为* a,outputtArr的尺寸应为* b。

在C#中,我尝试通过以下方式导入dll并调用functionA:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace Test{    
class Program
    {
     public delegate void costfun(ref int a, ref int b, double[] x, double[] fx);         
     static void Main(string[] args)
        {
            int a = 5, b = 3,
            double c= 1e-14

            double[] x = new double[5] { 1, 3, 5, 7, 9 };                              
            double[] y= new double[3] { 100, 100, 100 };
            costfun F = new costfun(fun);
          functionA(ref a, ref b,  ref c, x,y  Marshal.GetFunctionPointerForDelegate(F));

        }

        public static void fun(ref int na, ref int nb, double[] inX, double[] outY)
        {
            int i = 0;
            outY= new double[nb];

            if (outY.Length != nb)
            {
                //Console.WriteLine("output incorrect");
                return;
            }
            if (inX.Length != na)
            {
               // Console.WriteLine("input incorrect");
                return;
            }
            for (i = 0; i < nb; i++)
            { outY[i] = inX[i] * inX[i + 1] + 1; }
        }

        // import the dll
        [DllImport("cdll.dll", EntryPoint = "functionA", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]    
        public static extern void functionA(int* a, int* b, double*c,double[] inputArr, double[] outputtArr, IntPtr fcpointer);
}
}

程序成功编译,可以执行。但是我在执行过程中发现,每当从dll调用fun函数时,输入数组inX仅具有单个元素,即仅传递inX [0]。如果我在函数fun中注释了两个if语句,Visual Studio将由于在语句中发生索引超出范围的异常而中断:

outY[i] = inX[i] * inX[i + 1] + 1; 

因为inX [i + 1]。有人可以给我一些如何解决此问题的提示吗?谢谢

0 个答案:

没有答案
相关问题