Search code examples
c#cpinvokemarshalling

C# Marshall void* that is set to NULL


Trying to write a wrapper for a C DLL.

The C Native signature is:

BOOL WINAPI PBM_OpenCard (DWORD* CardHandle, TCHAR* CardName, void* Module, 
        DWORD ModuleId, WORD ShareFlags, WORD LoadFlags)

To which documentation says: "Module set to NULL - reserved"

This what my c# signature looks like:

public static extern  bool PBM_OpenCard(ref uint CardHandle,
        StringBuilder CardName, System.IntPtr Module, uint ModuleId,
        ushort ShareFlags, ushort LoadFlags) 

What do i pass in for the Module argument in my C# App? I tried using System.IntPrt.Zero and it compiled, but not sure if that is the right way to do it since I can't interface with the hardware at this point.


Solution

  • Your assumption is correct, IntPtr.Zero does correspond to C's NULL, just don't forget to set your .NET build away from AnyCPU to match the arch of the native method you're linking with.

    Protip: Use the [return: MarshalAs] attribute syntax to set the marshalling of BOOL to System.Boolean (though this is the default, it helps to be explicit). the same applies to your parameters as I see it's using TCHAR (which makes me die inside).

    Protip 2: Don't forget to modify the method signature to conform to .NET style conventions, including not using underscores in identifiers, PascalCase for publics and using camelCase parameter names. Also consider hiding native methods from all consumers and wrapping them in a safe IDisposable object.