There’s an old marshal in town… As in marshaling variable length array of structs from C (C, unmanaged code, etc) to VB.Net
This article presents an example of how to create a VB.NET program that retrieves data in the form of a variable length array of structs from a DLL file written in C. The challenge here is how to pass data between the safe world of managed code executed by the Common Language Runtime (CLR) and unmanaged code.
The code which is developed using the .NET Framework is known as managed code. This code is directly executed by CLR with the help of managed code execution. Any code that is written in .NET Framework is managed code. Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross-language debugging, and so on. Code which is developed outside the .NET Framework is known as unmanaged code. Applications that do not run under the control of the CLR are said to be unmanaged, and therefore don’t have the benefits of the CLR. I won’t get any deeper into the definitions of managed and unmanaged code since that is out of the scope for this article and there are plenty of sources for that on the internet. Just Google it :)
The solution for passing data between managed and unmanaged code is of course marshalling. What made the assignment a bit tricky was that some of the unmanaged functions returned an array of structs whose size I didn’t know when I was calling the function.
First I begin with the unmanaged DLL. Here is the struct declaration in C:
This is something I currently do only once in a blue moon, but I think that’s going to change in the coming year (i.e. good chance I’m going to playing in unmanaged API world’s) and so I wanted to capture this for future reference…
Related Past Post XRef:
Marshall Fixed Length TCHAR Strings between Managed and Unmanaged Code