1

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, i.e. 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.

2
  • That's not a real C++/CLI wrapper. You need to expose managed types in your C++/CLI function. So that the C# function can call it. You can tell that it's no good because your C++/CLI function does nothing. That function needs to adapt the C++ interface to be a .net interface. A word of advice, don't use unsafe code in the C#. You simply don't need to if you get the C++/CLI right. I wonder if you need the extra layer of C++/CLI. Did you consider p/invoke? Commented Dec 27, 2012 at 17:26
  • I am trying to decrease data copy as much as possible. What you mean is I guess copying from managed arrays to unmanaged arrays in the C++/CLI wrapper but I am really dealing with huge amounts of data. That's why I am using unsafe pointers. Commented Dec 27, 2012 at 17:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.