简体   繁体   中英

C# - DLLImport and function default values

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM