Member 13272199 Ответов: 1

Как работает класс C++ в C#? Это может быть простой пример


How work a C++ Class in C#? It could be a simple example

// My try:
// C++
***************
// Computing.h
#pragma once
class Computing
{
public:
	Computing();
	int Compute(int a, int b);
	~Computing();
***************
// Computing.cpp
#include "Computing.h"
Computing::Computing()
{
}
int Computing::Compute(int a, int b)
{
	return a + b;
}
Computing::~Computing()
{
}
***************
// main.h
#pragma once
#include "Computing.h"

extern "C"
{
	extern __declspec(dllexport) Computing* CreateComputingObject();
	extern __declspec(dllexport) void DeleteComputingObject(Computing* computing);
	extern __declspec(dllexport) int CallCompute(Computing* computing, int a, int b);
}
***************
// main.cpp
#include "main.h"
#include <cstddef>
#include "Computing.h"

extern "C" __declspec(dllexport) Computing* CreateComputerObject()
{
	return new Computing();
}

extern "C" __declspec(dllexport) void DeleteCountingObject(Computing* computing)
{
	if(computing != NULL)
	{
		delete computing;
		computing = NULL;
	}
}

extern "C" __declspec(dllexport) int CallCompute(Computing* computing, int a, int b)
{
	int res = 0;
	if(computing != NULL)
	{
		res = computing->Compute(a, b);
	}
	return res;
}
*****************
// C#
// Program.cs
using System;
using System.Runtime.InteropServices;

namespace MainProgram
{
    public class CSUnmanagedTestClass : IDisposable
    {
        [DllImport("CppDLL.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr CreateComputingObject();

        [DllImport("CppDLL.dll", CharSet = CharSet.Unicode)]
        public static extern void DeleteComputingObject(IntPtr computing);

        [DllImport("CppDLL.dll", CharSet = CharSet.Unicode)]
        public static extern int CallCompute(IntPtr computing, int a, int b);

        private IntPtr m_pNativeObject;

        public CSUnmanagedTestClass()
        {
            this.m_pNativeObject = CreateComputingObject();
        }

        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool bDisposing)
        {
            if (this.m_pNativeObject != IntPtr.Zero)
            {
                DeleteComputingObject(this.m_pNativeObject);
                this.m_pNativeObject = IntPtr.Zero;
            }

            if (bDisposing)
            {
                GC.SuppressFinalize(this);
            }
        }
        ~CSUnmanagedTestClass()
        {
            Dispose(false);
        }

        public void PassInt(int a, int b)
        {
            CallCompute(this.m_pNativeObject, a, b);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CSUnmanagedTestClass testClass = new CSUnmanagedTestClass();
            testClass.PassInt(42, 5);
            System.Console.WriteLine("The sting returned was: ");

            testClass.Dispose();

            Console.Read();
        }
    }
}


Что я уже пробовал:

How work a C++ Class in C#? It could be a simple example

Philippe Mori

Ваш вопрос не совсем ясен... Если вы хотите перевести код в код C#, то Решение 1-это правильный путь. Если приведенный выше код-это то, что вы до сих пор пытались использовать для взаимодействия между C# и C++, то вам нужно объяснить свою проблему. Кроме того, на практике лучшее решение во многом зависит от фактического кода C++, поскольку у вас много вариантов (код порта на C#, P/Invoke и смешанный режим C++, чтобы назвать несколько).

1 Ответов

Рейтинг:
1

OriginalGriff

"Перевод" вашего класса C# будет следующим:

public class Computing
   {
   public Computing() {}
   public int Compute(int a, int b)
      {
      return a + b;
      }
   }
...
   Computing comp = new Computing();
   Console.WriteLine("{0} + {1} = {2}", 10, 20, comp.Compute(10, 20));
(Строго говоря, вам не нужен конструктор без параметров в C#, он будет установлен по умолчанию для вас, если вы не предоставите никаких конструкторов)
Но это "плохой" C# - было бы лучше, как:
public static class Computing
   {
   public static int Compute(int a, int b)
      {
      return a + b;
      }
   }
...
   Console.WriteLine("{0} + {1} = {2}", 10, 20, Computing.Compute(10, 20));