.net - 如何在 C++\CLI 包装器中包装 (**) 类型

标签 .net c++-cli wrapper mixed-mode

我需要编写一个 C++\CLI 包装器。我的主要目标是处理我的 .NET 代码中提供的一些像素数据。该算法是用 C++ 编写的。

我有 dll 和 C++ 代码的 header ,我需要编写一个包装器才能在 C# 中使用 API。

C++ header

int Func1(unsigned short const* const* inputImage, int const* size, double const* res) ;

我不确定如何包装这种类型的方法。给定的 inputImage 实际上是指向多个串联图像像素数据的指针。

我的 wrapper.h

int Func1Wrapper(unsigned short const* const* inputImage, int const size, double const res);

我的 wrapper.cpp

int MyWrapper::Func1Wrapper(unsigned short const* const* inputImage,
    int const size, double const res){
        return Func1(inputImage, &size, &res);
}

如您所见,我在包装器中将 int const* size 替换为 int const size 并传递了 &size。这是正确的吗?

我应该如何包装 unsigned short const* const* inputImage?我知道我必须用其他类型替换此类型,以便在 C# 端易于使用。

另外,C# 代码中将使用哪种类型?

__type?__ inputImage;
int size = 512;
double res = 0;
myWrapperInstance.Func1Wrapper(inputImage, size, res);

C++ 用法示例

//The image data I need to initialize
struct imageData
{
    int sizes[3];
    double scales[3];
    double origin[3];
    short* buffer; // my Func1Wrapper will initialize this field
    unsigned short ** bufferSlices; // or this directly
};

// my data won't come from a file, but will be given to me as an inner image object, 
// so I will be filling the imageData struct on my own.
// In my question I'm trying to fill the imageslices or buffer - doesnt matter
void read_data(const char* filename, imageData& image){
    ImageReaderHandle reader_handler = MedisysImageReaders_Create(filename);
    int bufferSize = image.sizes[0] * image.sizes[1] * image.sizes[2];
    image.buffer = new short[bufferSize];
    MedisysImageReaders_ReadData(reader_handler, image.buffer, bufferSize);

    // MedisysImageReader outputs a short*, for this example, will be casted     into unsigned short without complete carless!
    image.bufferSlices = new unsigned short*[image.sizes[2]];
    int xySize = image.sizes[0] * image.sizes[1];
    for (int z = 0; z < image.sizes[2]; z++) image.bufferSlices[z] = (unsigned short*)(image.buffer + z*xySize);
}

最佳答案

第 1 部分相当简单。

在 C++ 中,int const* 是一个指向整数的只读指针。您可以拥有指向非常量整数的只读指针。这只是意味着您不能通过该指针进行写入,但您仍然可以通过其他方式更改指向的整数。因此,您的包装器不需要 int const size 中的 const。

但是,int const* 可以指向数组的第一个整数。这是一个语义约定,你不知道数组中有多少个整数。更令人担忧的是,在这种情况下,在名为 size 的参数之后有一个 double const* resres 很可能指向一个 size double 组。检查文档。

对于第 2 部分,您几乎知道图像将是一个数组。您可以在包装器中传递一个 unsigned short const* inputImage,然后传递 &inputImage 到底层函数。您需要在 C++/CLI 中固定数组以获得 unsigned short const*

关于.net - 如何在 C++\CLI 包装器中包装 (**) 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39095652/

相关文章:

c++ - "Unresolved Typeref-Token"与 SDL_net 和 .NET

c# - c++\cli 项目依赖的 c++ dll 未复制到 c# 输出目录

html - 我怎样才能让我的 wrapper 在特定部分向右流血?

.net - 关于学习哪些.NET ORM的一些建议

c# - 如果当前行宽已满,WinForm 换行

c# - 可选参数 “must be a compile-time constant”

c++ - 带异常的 C/C++ 标准库包装器

c++ - 仅当链接为 -static 时,才会从链接库调用包装函数

c# - 什么启动 Windows 服务安装程序的安装?

c# - 如何在 python 中加载 C# dll?