tags:

views:

279

answers:

2

I have a C DLL with an export that looks like the following:

__declspec(dllexport) int Function(
    char *password,
    unsigned char *ssid,
    int ssidlength,
    unsigned char *output)
{

On the C# side, I'm using this as follows:

[DllImport("myDLL.dll", SetLastError = true)]
protected static extern int Function(
    [MarshalAs(UnmanagedType.LPStr)] 
    string password,
    [MarshalAs(UnmanagedType.LPStr)] 
    string ssid,
    int ssidlength,
    [MarshalAs(UnmanagedType.LPArray)]
    byte[] output);

The above actually works just fine, but it took me awhile to figure out what things I needed to marshal as what. Is there any guides out there that just list all possible c/cpp datatypes and their equiv C# Marshalling?

Something like:
c => C#
Char *myVar => [MarshalAs(UnmanagedType.LPStr)] string myVar
...
but list all of the types?

Reason I ask, is because I never know when to use "ref" or out or IntPtr, or what type to marshal something as.

Lastly, In the above code, I'm marshalling a pointer to an unsigned char array as a long pointer to a string. This doesn't seem right, but it works. It makes more sense for this to end up in a byte[] array, but I can't get it to work. If only there was a online reference I could use...

+1  A: 

There are lots of guides on MSDN.

That being said, pinvoke.net and the PInvoke Interop Assistant are great resources for working with native code.

The interop assistant, in particular, often makes this very easy.

Reed Copsey