在C#中使用数组和指针与C DLL [英] Using arrays and pointers in C# with C DLL

查看:100
本文介绍了在C#中使用数组和指针与C DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的C#(刚开始在过去一周的学习)。

I am very new to C# (just started learning in the past week).

我已经写在C具有以下功能的自定义DLL:

I have a custom DLL written in C with the following function:

DLLIMPORT void test_function (double **test)

我所希望做的是必须从C#为阵测试。

What I am looking to do is have a pointer from C# for the array 'test'.

所以,如果在DLL函数我有测试[0] = 450.60,测试[1] = 512.99等等。我希望能有一个可在我的C#程序。

So, if in the DLL function I have test[0] = 450.60, test[1] = 512.99 etc. I want to be able to have that available in my C# program.

在C#程序我有类似的东西:

In the C# program I have something similar to:

namespace TestUtil
{
  public class Echo
  {
    public double[] results = new double[10];
    public double[] results_cpy = new double[10];


    [DllImport("test_dll.dll", CallingConvention = CallingConvention.Cdecl)]
    static extern unsafe void test_function(ref double[] Result);

    public unsafe void Tell()
    {
      results[0] = 0.0;
      results[1] = 0.0;

      results_cpy[0] = 0.0;
      results_cpy[1] = 0.0;

      test_function(ref results);
      results_cpy[0] = (double)results[0] + (double)results[1] ;
    }
  }
}

在DLL的test_function功能我用下面的:

In the DLL's 'test_function' function I used the following:

*test[0] = 450.60;
*test[1] = 512.99;

在DLL一切都OK(我用一个消息框在DLL中被应用到检查值)。早在C#程序的结果[0]'似乎都很正常,我可以从中获得价值,但'结果[1]给我一个索引越界的错误。我知道这是因为,如果我省略'+(双)结果[1]我收到任何错误。另外,如果我做的DLL中没有试图修改测试[1]它保留从C#原始值(在我的例子0.0)。

Within the DLL everything was OK (I used a message box within the DLL to check the values were being applied). Back in the C# program 'results[0]' appears to be fine and I can get values from it, but 'results[1]' gives me an index out of bounds error. I know this because if I omit '+ (double)results[1]' I receive no error. Also, if I make no attempt within the DLL to modify 'test[1]' it retains the original value from C# (in my example 0.0).

显然,我没有做正确的事情,但这是我已经能够去拥有它在所有的工作最接近的一次。别的我已经试过各种悲惨的失败了。

Obviously I am not doing something right but this is the closest I have been able to get to having it work at all. Everything else I have tried fails miserably.

任何帮助将大大AP preciated。

Any help would be greatly appreciated.

推荐答案

有没有需要不安全code。其实,没有必要通过引用都传递。如果你的签名是这样的:

There's no need for unsafe code. In fact, there's no need to pass by reference at all. If your signature looks like this:

void test_function (double *test)

和导入是这样的:

static extern void test_function(double[] Result);

然后一切都应该正常工作。也就是说,假设你只需要修改阵列并不会返回一个完全新的数组。

Then everything should work fine. That is, assuming you only need to modify the array and not return a completely new array.

这篇关于在C#中使用数组和指针与C DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆