求助:C# 委托转换成函数指针后,函数内部数组赋值失败问题

maiqing 2018-11-17 05:08:29
在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结果不正确。在网上找了很多资料,但是都没有描述类似的现象。希望有高手能指教
...全文
35 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
没有C这个functionA的api说明吗?
这个double* out指的是什么?有没有可能是输出的数组长度设置?
试下y赋不为0的值看有没有结果
xian_wwq 2018-11-19
  • 打赏
  • 举报
回复
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

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧