如何 return class 从 C++ 代码到 C#

How to return class from c++ code to c#

我正在从 C# 代码调用 C++ 方法。一切正常,除了 return 将多个参数返回到 C#。

在我的例子中,这些参数是:int x, y, width, height;

我想做的是return一个class或者从c++代码到c#的结构。

我提供了一个例子,这样我的想法会更清楚。我知道一种方法是使用 Marshal class,也许是唯一的方法。

C#代码

public class ImageMatch
{
    //method that is used to call pass string parameters and call c++ method
    [System.Runtime.InteropServices.DllImport("ImageComputingWrapper.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl)]
    static extern ImageComputingWrapper.ImageParams ComputeImage(string imgPath, string templPath);

    public  GetImgParams(string imgPath, string templPath)
    {
        //a class from C++ code
        ImageComputingWrapper.ImageParams imgParams;
        //retreive all the data
        imgParams = ComputeImage(imgPath, templPath);
    }
}

C++代码

//ImageComputingWrapper.cpp
extern "C" __declspec(dllexport) ImageComputingWrapper::ImageParams ComputeImage(const char* imgPath, const char* templPath)
{
    computeImage* compImage = new computeImage(imgPath, templPath);
    ImageComputingWrapper::ImageParams imageParams;

    imageParams.x = compImage->x;
    imageParams.y = compImage->y;
    imageParams.width = compImage->width;
    imageParams.height = compImage->height;

    return imageParams;
}

//ImageComputingWrapper.h
//class to return back to c#
public ref class ImageParams
{
    public:
        ImageParams(){}
        int x;
        int y;
        int width;
        int height;
};

我知道不可能像本例中那样从 C++ 代码 return class 到 C#。只是为了方便理解我的意思。

需要指出的一点是,我是一名 C# 程序员,因此该 C++ 代码(指针)中可能存在问题。

您不能 return 使用 p/invoke 引用 class。您可以做的是在 C++/CLI 程序集中声明一个 ref class,然后简单地从 C# 中使用它。

首先你需要一个 C++/CLI class 库。例如:

// ClassLibrary1.h

#pragma once

using namespace System;

namespace ClassLibrary1 
{
    public ref class Class1
    {
    public:
        int x;
        int y;
        int width;
        int height;
    public:
        Class1() : x(42), y(666), width(24), height(13) {}
    };
}

然后您可以像使用任何其他托管程序集一样使用此 class 库:

using System;
using ClassLibrary1;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 instance = new Class1();
            Console.WriteLine(instance.x);
            Console.WriteLine(instance.y);
            Console.WriteLine(instance.width);
            Console.WriteLine(instance.height);
        }
    }
}

仅此而已。


您在评论中询问如何将字符串参数传递给 C++/CLI 代码。在 C++/CLI 端使用 System::String^。这是引用 .net 字符串类型的 C++/CLI 方式。所以你的构造函数可能会变成:

public ref class Class1
{
....
public:
    Class1(System::String^ imgPath, System::String^ tempPath)
    {
        ....
    }
};

在 C# 端,您将像这样创建实例:

string imgPath = "...";
string tempPath = "...";
Class1 instance = new Class1(imgPath, tempPath);