none
Native enum and define available in c# RRS feed

  • Question

  • Hello,

     

    What is the best way to have enum and define from my native c++ header available in c# ? I have a native c++ dll with hundreds of #define and enum and I would like to have some of them available on my c# application. I'm currently using p/invoke to call my native C functions but I haven't find a clean way to have them on the c# side WITHOUT redefining them on the managed side. The only solution I can imagine is to create a C++/CLI managed layer in the middle and for the enum have a pre-processor definition in the native header file and include this header in my C++/CLI project. Something like below:

     

    Native c++: nativeCppHeader.h: 
    #ifdef _MANAGED 
    #define _ENUM public enum class 
    #else 
    #define _ENUM enum  
    #endif 
    #define DEFINE_UNMANAGED1   5 
     
    _ENUM ENUM_UNMANAGED 
        ELEMENT0 = 0, 
        ELEMENT01,  
        ELEMENT2, 
    }; 
     
     
    Managed C++/CLI managedCppHeader.h: 
    #include "TestEnum.h" 
     
    using namespace System; 
    using namespace System::Runtime::InteropServices; 
     
    namespace ManagedCppWrapper { 
     
        public ref class cManagedCppWrapper 
        { 
        public
     
            literal int DEF_UNMANAGED1= DEFINE_UNMANAGED1; 
     
            cManagedCppWrapper(){}; 
            ~cManagedCppWrapper() {}; 
        }; 
     
    C# myCSharpAp.cs: 
     
    using ManagedCppWrapper; 
    ... 
    int testCPPConst = cManagedCppWrapper.DEF_UNMANAGED1; 
                CPPMAN_ENUM cppEnumInCSharp = CPPMAN_ENUM.myMan1; 
                ENUM_UNMANAGED unManEnumInCSharp = ENUM_UNMANAGED.ELEMENT0; 
     

     

    Does that make sense or is there a better way to do that? Thank you very much for your help.

     

    -Steve


    Thursday, January 29, 2009 7:44 AM

All replies

  • That looks fine if you don't mind the extra layer.

     

    Another option might be to use some kind of code generation tool to generate C# and C++ defs from a common source.


    Mattias, C# MVP
    Thursday, January 29, 2009 1:03 PM
    Moderator
  • Agreed.  Swig is such a tool.  I don't know it well enough to know if tries to do anything with enums.  It surely won't handle defines.
    Hans Passant.
    Thursday, January 29, 2009 1:34 PM
    Moderator
  • Thank you for your suggestions.

    It would have been nice of course to avoid this extra layer but I haven't found how.

     

    About swig, I actually tried it ( actually I'm  using it a lot for c++ to TCL). It's working ok but the annoying thing is that it creates a new c# file for every new enum and/or class. So if you add a new enum on the c++ side you have to manually add the new c# generated file in your .net project. Not very convenient for on going developpment...

     

    Any other ideas ? Thanks.

     

    -Steve

    Thursday, January 29, 2009 4:45 PM