Example of manage C ++ packaging native C ++ class

Source: Internet
Author: User
Native C ++
   1:  #include 
 
   2:   
   3:  class CPPClass
   4:  {
   5:  public:
   6:    CPPClass(void) {};
   7:  public:
   8:    ~CPPClass(void) {};
   9:   
  10:    void produceByteArray(unsigned char* array, int length)
  11:    {
  12:      printf("CPPClass: Producing %i elements/n", length);
13: For (INT I = 0; I
 
  
  14:      {
  15:        array[i] = i*2;
  16:      }
  17:    }
  18:  };

Managed C ++ After packaging

   1:  using namespace System;
   2:  #include "CPPClass.h"
   3:   
   4:  namespace SimpleInterop
   5:  {
   6:    public ref class ManagedWrapperClass
   7:    {
   8:    public:
   9:      ManagedWrapperClass(void) { _pCPPClass = new CPPClass(); };
  10:   
  11:      // Wrapper method for the produceByteArray C++ method
  12:      // array
   
    ^ represents a managed byte array
   
  13:      void produceByteArray(arraybyte>^ data)
  14:      {
  15:        // The following line fixes the managed array to a pointer. This avoids
  16:        // that the address of the array is changed by the garbage collector.
  17:        pin_ptrbyte> p = &data[0];
  18:        _pCPPClass->produceByteArray(p, data->Length);
  19:      }
  20:   
  21:    private:
  22:      CPPClass* _pCPPClass;
  23:    };
  24:  }

Use in C #

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:   
   5:  namespace SimpleInterop
   6:  {
   7:    class Program
   8:    {
   9:      static void Main(string[] args)
  10:      {
  11:        ManagedWrapperClass CPPClass = new ManagedWrapperClass();
  12:   
  13:        // Test the produceByteArray method
  14:        byte[] data = new byte[10];
  15:        CPPClass.produceByteArray(data);
  16:        foreach (byte element in data) { Console.WriteLine(element); }
  17:   
  18:        Console.WriteLine("Press return");
  19:        Console.Read();
  20:      }
  21:    }
  22:  }

Original: http://blog.naiznoiz.com/2008/01/cc-interop-a-simple-example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.