Using arrays and pointers in C# with C DLL

29,635

Solution 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.

Solution 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).

Share:
29,635
JaredPar
Author by

JaredPar

Developer at Microsoft working on a language and operating system incubation project. Sites VsVim - VsVim on Visual Studio Gallery Blog - http://blog.paranoidcoding.com/ Twitter - http://twitter.com/jaredpar Linked In - http://www.linkedin.com/in/jaredpar Google+ - +JaredParsons Email: [email protected]

Updated on July 06, 2022

Comments

  • JaredPar
    JaredPar about 2 years

    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.