Calling C++ Library from C# with C++/CLI Wrapper

I have a C++ library, header of which looks like:

void NotMyFun(double * a, int * b);

The function reads from a , and writes to b . To call the library I have created a C++/CLI wrapper, where below function is defined:

static void MyWrapperFun(double * a, int * b)
{
    NotMyFun(a,b);
}

and works OK. From C# code, say, I have two managed arrays, ie double[] ma and double[] mb , where ma already holds some meaningful data, and mb is -meaningfully- filled when wrapper is called. Is below an OK way to call the wrapper function?

unsafe
{
    fixed (double* pma = ma)
    {
        fixed (int* pmb = mb)
        {
            MyWrapperNS.MyWrapperClass.MyWrapperFun(pma,pmb);
        }
    }
}

Are the unsafe pointers a fast way? Is any data copying involved here while passing and retrieving to/from C++/CLI wrapper? Or pointers are already pointing to a continuous memory space in C# arrays?

Besides, do I need any manual memory cleaning here? If the pointers are tied to the memory of managed C# arrays, I guess they are properly garbage collected after, but just want to be sure.


Personally I think you are over-complicating things. I'd avoid the unsafe code and skip the C++/CLI layer. I'd use a simple p/invoke declared like this:

[DllImport(@"mylib.dll")]
static extern void NotMyFun(double[] a, int[] b);

Because double and int are blittable types, no copying is necessary. The marshaller just pins the arrays for the duration of the call.

链接地址: http://www.djcxy.com/p/27806.html

上一篇: 指向C ++ / CLI包装器的指针

下一篇: 使用C ++ / CLI包装从C#调用C ++库