Problems importing DLLs with BYTE * output

I am importing a function from an unmanaged DLL in C #. The signature of a C ++ function is as follows

int RF_PowerOnEx(int nDev, int nCardType, DWORD* pdwRXSize, BYTE* lpbRXData) 

I import it as follows

 [DllImport("TP9000.dll")] public static extern int RF_PowerOnEx(int nDev, int nCardType, out int pdwRXSize, out byte[] lpbRXData); 

However, this gives me a System.AccessViolationException exception. I have successfully imported other functions besides this specific one. Both pdwRXSize and lpbRXData are processed as output. The integer and buffer are initialized, then passed to the function, which then fills the buffer. Help!!!! It seems I can pass the input parameters to the DLL, but I cannot get the output parameters. I tried passing the Stringbuilder object to no avail. Can anybody help me? Thanks!

Edit: Typo

+4
source share
3 answers

I would suggest you declare a managed signature as follows

 public static extern int RF_PowerOnEx(int nDev, int nCardType, out int pdwRXSize, [out] IntPtr lpbRXData); 

and then select the byte array β€œmanually” directly from unmanaged memory using the length information that must be set in pdwRXSize .

You really need to know more about the implementation of the function: in particular, the caller must do something to free up memory containing the data buffer?

+2
source

This is not out byte[] , which is equivalent to BYTE **. Do it just byte []. And pdwRXSize ref , set it to the size of the array. Call it that:

 byte[] buffer = new byte[666]; int size = buffer.Length; int retval = RF_PowerOnEx(device, cardtype, ref size, buffer); if (retval == okay) processData(buffer, size); 

You need to make an educated guess about the required size of the array.

+1
source

EntryPointNotFoundException because the name of your .NET declaration does not match the unmanaged declaration (due to underscore).

Try:

  [DllImport("TP9000.dll", EntryPoint = "RF_PowerOnEx")] public static extern int RFPowerOnEx(int nDev, int nCardType, out int pdwRXSize, out byte[] lpbRXData); 
0
source

All Articles