C++/CLI wrapper for .NET assembly (CppCLINETAssemblyWrapper)

The code sample demonstrates using C++/CLI to wrap a .NET class library. Your native C++ project can import the C++/CLI wrapper to indirectly call the .NET class library

4 Star
9,958 times
Add to favorites
E-mail Twitter del.icio.us Digg Facebook
Sign in to ask a question

  • How to extend this wrapper example with unmanaged data type struct?
    1 Posts | Last post April 15, 2013
    • T1T
      This CSSimpleObjectWrapper example works perfectly for a simple type like a float.
      How can I extend this example so it can use a struct like this one?
      Unmanaged C++ struct:
      #pragma pack (push, 4)
      struct STR_TEST_cpp
         short  s1;
         int    i1;
         float  f1;
         double d1;
         short  s2;
         int    i2;
         float  f2;
         double d2;
      #pragma pack (pop)
      Managed C# struct:
         [StructLayout(LayoutKind.Sequential, Pack = 4, Size = 32, CharSet = CharSet.Ansi)]
         public struct STR_TEST_CS
            public short s1;
            public int i1;
            public float f1;
            public double d1;
            public short s2;
            public int i2;
            public float f2;
            public double d2;
      I have tried several scenarios, but none of them works. And COM is not an option in my case.
      The example with the least compilation problems was this:
      STR_TEST_cpp CSSimpleObjectWrapper::get_StructProperty(void)
         GCHandle h = GCHandle::FromIntPtr(IntPtr(m_impl));
         CSSimpleObject ^ obj = safe_cast<CSSimpleObject^>(h.Target);
         STR_TEST_cpp structVal;
         marshal_context ^ context = gcnew marshal_context();
         const char *pszBuffer = context->marshal_as<const char*>(obj->StructProperty);
         memcpy (&structVal, pszBuffer, sizeof(STR_TEST_cpp));
         delete context; // This will also free the memory pointed by pszStr
         return structVal;
      void CSSimpleObjectWrapper::set_StructProperty(STR_TEST_cpp structVal)
         GCHandle h = GCHandle::FromIntPtr(IntPtr(m_impl));
         CSSimpleObject ^ obj = safe_cast<CSSimpleObject^>(h.Target);
         STR_TEST_CS ^ StructVal_CS = marshal_as<STR_TEST_CS ^>(structVal);
         obj->StructProperty = StructVal_CS;
      // cannot convert parameter 1 from 'CSClassLibrary::STR_TEST_CS ^' to 'CSClassLibrary::STR_TEST_CS'
      marshal_as derived from http://msdn.microsoft.com/en-us/library/bb531313.aspx:
      Thanks for any help!