DeviceIoControl & USB using Managed C++ & C#

Getting Started

I started writing the code in C# using Platform Invoke, but was having some problems creating all the data structures to be used with DeviceIoControl.  I decided to write this code in managed C++ instead. When I first started using managed C++, I created .h and .cpp files, just like I did when using unmanaged C++.  I compiled dozens of unmanaged C++ classes and my new managed C++ wrapper code into a managed library dll.  To get it all to work properly I got rid of the Stdafx files and turned off precompiled headers.  When starting work on the USB code, I decided to eliminate the .h files in managed code.  This way the managed C++ code is structured much the same as the C# code.  Since this worked well here, I plan to try this technique on my legacy code wrapper as well.

At first I thought that I would need to have two versions of my data structures, one for the unmanaged code and one for the managed code.  As it turns out, it is easy to create structures in managed C++ and use them in both the C++ & C# code.  I am creating a C++ wrapper function for each USB function, which avoids the problems that I was having with passing different types of data structures to DeviceIoControl using Platform Invoke.

The include files in the managed C++ module:

#include "stdafx.h"  which contains:

  • #using <mscorlib.dll> which is the core of .NET
  • #include <windows.h> for the win32 API
  • #include <stdio.h> After all these years of using C++, I still like the I/O routines I used in C.

#using <UsbCs.dll> some C# classes which I use from the managed C++ code.
#include "ezusbsys.h" Comes with the Cypress development board
#include "usb100.h" Found in the Device Driver Kit, and contains the definitions for constants & structures used when working with the USB.

When using assemblies in managed C++ you need a #using <mydll.dll> statement in your code and need to tell the compiler where to find the assembly, using the Resolve #using References field in the properties for the project.

Then you have the using namespace statements:

using namespace System;
using namespace System::Text;
using namespace System::Runtime::InteropServices;

After programming in C# for a while, putting those double colons in there, takes some getting use to, even for an old C++ guy.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“A computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are, in short, a perfect match” - Bill Bryson