views:

64

answers:

1

I'm interfacing with a native 3rd party C++ DLL via C# and the provided interop layer looks like below:

C#:

[DllImport("csvcomm.dll")]
public static extern int CSVC_ValidateCertificate(byte[] certDER, int length);

C++:

CSVC_Status_t CSVCOMM_API CSVC_ValidateCertificate(BYTE* certDER, DWORD length, 
    DWORD context = CONTEXT_DEFAULT);

Note, there are only two parameters in the C# extern definition since the the C++ function provides a default value for the third parameter. Is this correct? I was receiving some non-deterministic results when using the provided definition, but when I added the third parameter like below, it seems to be working correctly each time rather than sporadically.

[DllImport("csvcomm.dll")]
public static extern int CSVC_ValidateCertificate(byte[] certDER, int length, 
    int context);

Any ideas? Would the addition of the 3rd parameter really fix this issue?

+5  A: 

The optional parameter in C++ is resolved at compile time. When you call into this via P/Invoke, you need to always specify all three parameters.

If you want to have an optional parameter, you'll need to make a C# wrapper around this method with an overload that provides the optional support (or a C# 4 optional parameter). The actual call into the C++ library should always specify all three arguments, however.

Reed Copsey
OK, I thought that would be the case which is why I added the third parameter. It's still strange to me that the call seems to still work around half the time w/o it.
Taylor Leese
@Taylor: You're C++ function is probably reading memory beyond the second argument, and getting garbage data for the third argument (since it expects it to be there). This may work at times, but since its just feeding garbage, it will not be reliable (or correct).
Reed Copsey