Tuesday, March 20, 2007

Using unmanaged C in a managed world

I'm having a problem.

And it's a dozy.

My company is working with some Norwegians to produce a product - and we're making a software bit of it, utilizing libraries that they created.

Sounds reasonable so far.

Well, we're a .NET shop - and more specifically a VB.Net shop. While I was big on C++ in college, those days are long past. Nearly everything I need to do, can be done in VB. And for those odd bits that are left over, I usually employ C#.

Well, this library which we're having to use is built in C.

Without classes. Without structures. Without the STD.

For example, there's a function with this declaration in the header file:

short SW_getVersion(char* version);

As you might have guessed - the short that the function returns just tells us if the function was successful or not. The actual data we care about is being passed through that char pointer.

Beautiful huh?

Actually, it's not that bad. Or at least it wasn't until I started trying to use it in the managed world of .NET.

My first attempts in C#/C++ .NET 2.0 met with the unreasonable compiler error that libcd.lib was no longer supported. Since that was compiled directly into the library's I could do nothing.

So I went down to .NET 1.1.

It compiled, and i tried to link the DLL into my VB.Net front end - and quickly discovered that none of the functions which used c-style strings were accessible.

So, I went and started writing wrapper functions for the library functions which returned managed classes filled with relevant data. Which is when I discovered that managed code does not like talking to unmanaged code.

First C#, despite having the "UNSAFE" flag really doesn't do it. It's only, truly, possible to work in managed/unmanaged code side-by-side in C++.

No Big deal, I thought. After all, C++ was the language we used in college.

Famous last words. I'm now on day three of this fiasco, and am just beginning to get to a point where I can use the function listed above. Yet, I'm still not certain if I'm building these things correctly. Which means that I'm spending a whole bunch of time doing research on MarshalAs, IntPtr and P/Invoke.

And trying my best to figure out where the CString class is stored, so I can use the proper library to try playing with that.

Good times. :|

No comments:

Blog Widget by LinkWithin