Managed C++ to form a bridge between c# and C++

后端 未结 2 1518
独厮守ぢ
独厮守ぢ 2020-12-13 07:50

I\'m a bit rusty, actually really rusty with my C++. Haven\'t touched it since Freshman year of college so it\'s been a while.

Anyway, I\'m doing the reverse of wha

2条回答
  •  既然无缘
    2020-12-13 08:24

    Create a new C++/CLI project in visual studio and add a reference to your C# dll. Assume we have a C# dll called DotNetLib.dll with this class in:

    namespace DotNetLib
    {
        public class Calc
        {
            public int Add(int a, int b)
            {
                return a + b;
            }
        }
    }
    

    Now add a CLR C++ class to your C++/CLI project:

    // TestCPlusPlus.h
    
    #pragma once
    
    using namespace System;
    using namespace DotNetLib;
    
    namespace TestCPlusPlus {
    
        public ref class ManagedCPlusPlus
        {
        public:
            int Add(int a, int b)
            {
                Calc^ c = gcnew Calc();
                int result = c->Add(a, b);
                return result;
            }
        };
    }
    

    This will call C# from C++.

    Now if needed you can add a native C++ class to your C++/CLI project which can talk to the CLR C++ class:

    // Native.h
    #pragma once
    
    class Native
    {
    public:
        Native(void);
        int Add(int a, int b);
        ~Native(void);
    };
    

    and:

    // Native.cpp
    #include "StdAfx.h"
    #include "Native.h"
    #include "TestCPlusPlus.h"
    
    Native::Native(void)
    {
    }
    
    Native::~Native(void)
    {
    }
    
    int Native::Add(int a, int b)
    {
        TestCPlusPlus::ManagedCPlusPlus^ c = gcnew TestCPlusPlus::ManagedCPlusPlus();
        return c->Add(a, b);
    }
    

    You should be able to call the Native class from any other native C++ dll's as normal.

    Note also that Managed C++ is different to and was superceeded by C++/CLI. Wikipedia explains it best:

    http://en.wikipedia.org/wiki/C%2B%2B/CLI

提交回复
热议问题