如何将类从 C++ 代码返回到 C#

Mr.*_*ond 4 c# c++-cli dllimport

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

在我的情况下,这些参数是: int x, y, width, height;

我想要做的是将一个类或结构从 c++ 代码返回到 c#。

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
};
Run Code Online (Sandbox Code Playgroud)

我知道不可能像在这个例子中那样将类从 C++ 代码返回到 C#。只是为了容易理解我的意思。

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

Dav*_*nan 5

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

首先,您需要一个 C++/CLI 类库。例如:

// 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) {}
    };
}
Run Code Online (Sandbox Code Playgroud)

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

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是全部。


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

public ref class Class1
{
....
public:
    Class1(System::String^ imgPath, System::String^ tempPath)
    {
        ....
    }
};
Run Code Online (Sandbox Code Playgroud)

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

string imgPath = "...";
string tempPath = "...";
Class1 instance = new Class1(imgPath, tempPath);
Run Code Online (Sandbox Code Playgroud)