Using arrays and pointers in C# with C DLL

2019-02-15 23:20发布

问题:

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

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

DLLIMPORT void test_function (double **test)

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

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.

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] ;
    }
  }
}

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

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

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.

Any help would be greatly appreciated.

回答1:

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)

and your import looks like this:

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.



回答2:

I'm guessing you already know C++; if that's the case, you really should look at C++/CLI which lets you easily use managed code (.NET) from C++. The code you've shown above really isn't very C#-like (you should completely avoid unsafe).



回答3:

I am not sure what is going wrong, but I can certainly point you to an article that talks about p/invoke. see if this helps you.

http://msdn.microsoft.com/en-us/magazine/cc164123.aspx



回答4:

Similar question on SO here. Your looking at an opaque pointer, so it's likely a by-ref system InPtr as described in the other thread.

By the way, why not make it a double* instead of double**. That would make life easier, I think.