Techniques to keep corresponding native and managed enumerations in sync
I have a manager wrapper for a native library -- the native library is C++ with an exported C interface, and I use P/Invoke on the managed to side to achieve the interop. I am in control of both the managed and native code.
There's an enumeration in the native code that has a corresponding enumeration in managed code, something like this:
// C#
public enum ErrorCode {
None 开发者_Go百科= 0,
General = 1,
BadThings = 2,
HardDriveWasRemoved = 3,
}
// C++
enum ERROR_CODE {
ERROR_CODE_NONE = 0,
ERROR_CODE_GENERAL = 1,
ERROR_CODE_BAD_THINGS = 2,
ERROR_CODE_HARD_DRIVE_REMOVED = 3,
}
These enumerations need to be kept in sync, because the enumeration values are passed back and forth between managed and native code; an incorrect mapping between them causes subtle failures that aren't always immediately obvious.
Does anybody have any clever (but relatively light-weight) techniques for either (a) automatically keeping these enumerations in sync, or (b) providing a warning/error/failure as early as possible that the enumerations are out of sync?
Place them into a separate C# file, #include from C++ side. #define away all the C# fluff (like the initial public
). Like this:
#define public
#include "enums.cs"
#undef public
Reminds me of a music joke: How do you get two piccolo players to play in tune? A: Shoot one.
Could you just register the native DLL for COM, then reference and use the C++ enum in the C# code? I realize the naming conventions are a little off, but overall, just having one enum seems the simplest way to achieve what you want.
精彩评论