【发布时间】:2015-02-02 20:21:16
【问题描述】:
我正在从 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);
}
}
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++ 代码返回到 C#。只是为了方便理解我的意思。
需要指出的一点,我是一名 C# 程序员,所以 C++ 代码(指针)可能有问题。
【问题讨论】:
-
这是一个 System::Drawing::Rectangle。使用 C++/CLI 的目的是不必在你的 C# 程序中使用 [DllImport]。只需添加对 C++/CLI 项目的引用。你现在只会看到 ImageParams,你已经知道如何写一个真正的 ImageComputingWrapper