Using an unmanaged DLL with C#

2

I'm using a Silicon Labs VCP (CP2105) under Windows (7/8/10) and I am trying to obtain some info from it using the Silicon Labs runtime DLL - which is unmanaged.

This is my implementation:

[DllImport("CP210xRuntime.dll")]

private static extern Int32 CP210xRT_GetDeviceProductString(IntPtr handle, IntPtr bfPtr, ref uint len, bool convert);
public static Int32 GetProduct(IntPtr handle)
    {
        var buff = new char[100];           
        GCHandle hnd = GCHandle.Alloc(buff);
        IntPtr bfPtr = (IntPtr)hnd;
        uint bytesRead = 0; 
        var r = CP210xRT_GetDeviceProductString(handle, bfPtr, ref bytesRead, true);
        hnd.Free();
        return r;
    }

I am getting the device handle for the ports using:

  [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateFile(
             string FileName,
             uint DesiredAccess,
             uint ShareMode,
             IntPtr SecurityAttributes,
             uint CreationDisposition,
             uint FlagsAndAttributes,
             IntPtr hTemplateFile
    );

When I run this it works - of sorts, that is to say the return value is 0 which, according to the Silicon Labs docs, indicates all is well, and I have confirmed this by using a handle to another device and I got 3 back, which confirms invalid handle.

The bytesRead ref value is also ammended as expected to 36 which is what the length of the product name should be. But the buff array never fills with any data (just to be sure I have written values to each element as well but they dont change). If I leave the program running the whole thing throws an exception:

Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in********

Additional information: The runtime has encountered a fatal error. The address of the error was at 0x70338780, on thread 0x1f5c. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

This is also the program does, if I comment out the line where I call the function from the dll - the program does not fail.

I'm not massively familar with invoke unmanged code using C# so if someone could help me out with where I am going wrong / point me in the right direction I would be most grateful!

This is from the Silicon Labs Docs:

CP210x_STATUS CP210xRT_GetDeviceProductString(HANDLE cyHandle, 
LPVOID lpProduct, LPBYTE lpbLength, BOOL bConvertToASCII = TRUE)
c#
asked on Stack Overflow Nov 13, 2018 by Microkid • edited Nov 13, 2018 by marc_s

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0