将Mat从C ++ dll返回到VB.Net

时间:2014-02-12 04:39:16

标签: c++ .net vb.net opencv

我在C ++中编写了一个函数,该函数接受Mat类对象并在处理后返回Mat。我想将它集成到用VB.NET编写的UI

我在C ++中编写了这段代码

extern "C" _declspec(dllexport) Mat cropImage(Mat matA){
     Mat matB = processingObject.doSomething(matA);
     return matB;
}

processingObject.doSomething(matA)工作正常。

如何在VB中使用此dll?我不介意更改C ++代码以使其工作。

由于

更新>>>>

找到问题的解决方法。不是100%我想要的是什么

C ++

extern "C" __declspec(dllexport) int* cropImage(char* path, int& size)
{
    Mat matA = pavObj.cropped_liquid_region(path);

    int rows = matA.rows;
    int cols = matA.cols;
    int channels = matA.channels();

    int length = rows*cols*channels + 3;
    size = length;
    int* arr = new int[length];

    arr[0] = rows;
    arr[1] = cols;
    arr[2] = channels;

    Mat layer[3];
    split(matA, layer); // split into color layers BGR
    int count = 3;

    for(int i=0;i<3;i++){
        for(int j=0;j<layer[i].rows;j++){
            for(int k=0;k<layer[i].cols;k++){
                arr[count] = layer[i].at<uchar>(j, k);
                count++;
            }
        }
    }

    return arr; 
}

extern "C" __declspec(dllexport) int ReleaseMemory(int* pArray)
{
    delete[] pArray;
    return 0;
}

VB签名

<DllImport("mat.dll", CallingConvention:=CallingConvention.Cdecl)> _
Public Shared Function cropImage(ByVal path As String, ByRef sz As Integer) As IntPtr
End Function

<DllImport("mat.dll", CallingConvention:=CallingConvention.Cdecl)> _
Public Shared Function ReleaseMemory(ByVal ptr As IntPtr) As Integer
End Function

VB调用dll

Dim size As Integer
Dim ptr As IntPtr = cropImage(path, size)
Dim result(size) As Integer
Marshal.Copy(ptr, result, 0, size)
ReleaseMemory(ptr)

所以基本上发生的是图像的内容被带到一维数组并传递到管理端,在那里再次重建图像。

1 个答案:

答案 0 :(得分:1)

您需要在C#端使用DllImport调用来调用

http://msdn.microsoft.com/en-us/library/aa984739(v=vs.71).aspx
How to use <DllImport> in VB.NET?
http://www.codeproject.com/Articles/552348/C-23-2fCplusinteroppluswithplusDllImport

它的要点是,你需要像这样输入你的dll:

<System.Runtime.InteropService.DllImport("mat.dll", _
SetLastError:=True, CharSet:=CharSet.Auto)> _
<< VB Signature of your cropImage function >>

您可能还需要进行一些参数编组,以便在VB和C ++之间“翻译”您的Mat类型