在c编译的动态链接库中,定义有以下函数
__declspec(dllexport) void __stdcall  functionA(
    int* a,
    int* b,
    double *c,
    double[] inputArr,
    double* out,
    void(*fun)(int*, int*,double[],double[])
)在函数functionA 内部, 数组inputArr以及 a 与b,将会传递给函数指针fun,fun 通过计算,将结果存在另外一个数组里。在c# 中,为了调用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=0;
            costfun F = new costfun(funCSharp);
          functionA(ref a, ref b,  ref c, x,ref y  Marshal.GetFunctionPointerForDelegate(F));        }        public static void funCSharp(ref int na, ref int nb, double[] inX, double[] outY)
        {
            int i = 0;
           
            for (i = 0; i < outY.Length; i++)
            { outY[i] = outY[i] * outY[i]; }        }        // 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* out, IntPtr fcpointer);
}
}上述代码可以成功编译并执行。但是执行过程中发现,在C 的dll函数里执行funCSharp的时候,该函数的输出数组outY始终为0, 导致functionA结果不正确。在网上找了很多资料,但是都没有描述类似的现象。希望有高手能指教

解决方案 »

  1.   

    1.DllImport
    改为
      [DllImport("cdll.dll", EntryPoint = "functionA", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]    
       public static extern void functionA(ref int a,ref int b,ref double c,double[] inputArr, double* out,[In] costfun func);
    2.看c api声明,
    输出数据应该是放在double *out了
    如果double *out返回的是数组
    那么 double y=0定义是不对的。
    需要定义数组,传入数组而不是double类型变量
    3.
     
    public static void funCSharp(ref int na, ref int nb, double[] inX, double[] outY)
            {
                int i = 0;
                
                for (i = 0; i < outY.Length; i++)
                { outY[i] = outY[i] * outY[i]; }
     
            }这个逻辑个人分析是有问题的,应该是通过对inX的处理,输出到outY
    outY本身就是0,那么再怎么算,输出还是0
      

  2.   

    没有C这个functionA的api说明吗?
    这个double* out指的是什么?有没有可能是输出的数组长度设置?
    试下y赋不为0的值看有没有结果