Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DLLImport Int** - How to do this if it can be done

I am trying to use a third party DLL that wants an int** as one of the parameters to the method. It describes the parameter as the address of the pointer that will point to the memory allocation.

Sorry for any confusion. The parameter is two-way I think. The DLL is for talking to an FPGA board and the method is setting up DMA transfer between the host PC and the PCI board.

like image 235
Robin Robinson Avatar asked Oct 16 '08 16:10

Robin Robinson


People also ask

How does DllImport work?

DllImport attribute uses the InteropServices of the CLR, which executes the call from managed code to unmanaged code. It also informs the compiler about the location of the implementation of the function used.

Why we use extern keyword in C#?

Using the extern modifier means that the method is implemented outside the C# code, whereas using the abstract modifier means that the method implementation is not provided in the class. The extern keyword has more limited uses in C# than in C++.

What is IntPtr C#?

The IntPtr type can be used by languages that support pointers and as a common means of referring to data between languages that do and do not support pointers. IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System. IO.

What overarching namespace provides P invoke to net?

Most of the P/Invoke API is contained in two namespaces: System and System. Runtime.


2 Answers

Use a by-ref System.IntPtr.

 [DllImport("thirdparty.dll")]
 static extern long ThirdPartyFunction(ref IntPtr arg);

 long f(int[] array)
  { long retval = 0;
    int  size   = Marshal.SizeOf(typeof(int));
    var  ptr    = IntPtr.Zero;

    try 
     { ptr = Marshal.AllocHGlobal(size * array.Length);

       for (int i= 0; i < array.Length; ++i) 
        { IntPtr tmpPtr = new IntPtr(ptr.ToInt64() + (i * size));
          Marshal.StructureToPtr(array, tmpPtr, false);
        }

       retval = ThirdPartyFunction(ref ptr);
     }
    finally 
     { if (ptr != IntPtr.Zero) Marshal.FreeHGlobal(ptr);
     }

    return retval;
  }
like image 130
Mark Cidade Avatar answered Nov 11 '22 11:11

Mark Cidade


You will have to make use of the Marshal class or go unsafe in this case.

It could also just be a pointer to an array, so a ref int[] list might work.

like image 40
leppie Avatar answered Nov 11 '22 12:11

leppie