How to pass the pointer to array from C# to C dll.


  • I have tried to access the function in C dll which has the following signature,


    1 int FAR PASCAL_CONV swe_houses(double tjd_ut,   
    2     double geolat,  
    3     double geolon,  
    4     int hsys,  
    5     double *cusp,  
    6     double *ascmc) 

    In the above parameters the cusp and ascmc should be pointer to the array.

    The VB6 call is as follows

    Private Declare Function swe_houses Lib "swedll32.dll" _  
            Alias "_swe_houses@36" ( _  
              ByVal tjd_ut As Double, _  
              ByVal geolat As Double, _  
              ByVal geolon As Double, _  
              ByVal ihsy As Long, _  
              ByRef hcusps As Double, _  
              ByRef ascmc As Double _  
            ) As Long 

    I have written the same in C# as follows

    [DllImport("swedll32.dll", EntryPoint="_swe_houses@36" ,CharSet = CharSet.Unicode)]  
    public unsafe static extern long shsLib (  
            double tjd_ut,  
            double geolat,  
            double geolon,  
            long ihsy,   
            double[] hcusps, // hcusps must be first of 13 array elements  
            double[] ascmc); // ascmc must be first of 10 array elements  

    I have called the above function as given below

    double[] hCusps = new double[13];  
    double[] hAmcs = new double[10];  
    swe_houses(123456, 79.9, 80.4, 0, hCusps, hAmcs); 

    But it throws a null reference exception.

    Please let me know how to pass the pointer to array from C# to C dll.

    Thanks in advance.

    Thursday, November 06, 2008 2:44 PM


All replies

  • Nothing wrong with the array parameters, but try changing ihsy from long to int. Same with the function's return type.

    Mattias, C# MVP
    Thursday, November 06, 2008 3:27 PM
  • Thanks Mattias,

    It is working.
    Friday, November 07, 2008 3:57 AM
  • Could you please let me know why the same (long type) works fine in VB6 code and not in C#?
    Friday, November 07, 2008 3:59 AM
  • Long in VB6 is a 32-bit integer.

    long in C# is a 64-bit integer (and int is 32 bits).

    Mattias, C# MVP
    Friday, November 07, 2008 8:53 AM
  • Thanks.
    Friday, November 07, 2008 9:29 AM
  • Hi Vijay

    I am new to C# & OOP, my experience is mainly simple perl scripts.

    I am wondering if by now you might have a C# solution to calling Longitudes from the swedll32.dll available for study.



    Sunday, October 03, 2010 6:08 PM