I'm implementing a C++ DLL that needs to read/write data to the serial line. The usage of this DLL is in a C# application. Currently I can't manage to read data from the C# application while i'm using the C++ read code (without the C# wrapper the read function works properly).
C++ code:
extern "C" __declspec(dllexport) int Read(void *Buffer, unsigned int MaxNbBytes, unsigned int TimeOut_ms)
{
return uart.Read(Buffer, MaxNbBytes, TimeOut_ms);
}
C# Code
[DllImport("RS232LIB.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern int Read(out byte[] bytesRead, int maxNbBytes, int timeOutMs);
var bytes = new byte[4];
Read(out bytes, 4, 10);
After running those line i keeps getting the System.AccessViolationException.
How can I solve this issue?
Remark: I can't use the C# Serial class. My C++ serial function works well.
The uart.Read(void *Buffer, unsigned int MaxNbBytes, unsigned int TimeOut_ms) reference:
\Buffer : array of bytes read from the serial device
\MaxNbBytes : maximum allowed number of bytes read
\TimeOut_ms : delay of timeout before giving up the reading
unsigned int- shouldn't the C# counterpart then useuint?out. Pass bytes.Length as the 2nd argument so you can never get it wrong. And don't ignore the return value, it probably tells you how many bytes it copied into your array.uintsignature tointand removed theout. There is no exception but i'm getting garbage data from the line.