user1884325
user1884325

Reputation: 2550

Is this an ok way of calling a C++ function from C#?

I am not super experienced in interlanguage calls between C# and C++. However, I created a VS2013 solution with 2 projects. One project is a C# project. The other project is a C++ project (DLL with CLR). I would like to know if my example code looks ok? The example is just showing how to pass down some values from C# to C++ . The C++ function prints out the values and writes into the output array. I verified that it works, but I'm wondering if there's something I missed and should be aware of and/or careful about?

           /* This is the code in my C# file */
           int val1 = 3;
           int val2 = 4;
           int[] input = new int[10] {1,2,3,4,5,6,7,8,9,10};
           int[] output = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
           thisInstance = new DSPClassProxy();
           thisInstance.myMethod(val1, val2, input, output);

This is how 'myMethod' is declared in my .h file:

void myMethod(int val1, int val2, array<int>^ in, array<int>^ output);

And this is the implementation of that function (in my .cpp file):

 void ClassProxy::myMethod(int val1, int val2, array<int>^ in, array<int>^ output)
{

     /* Call regular C function */
     myNativeMethod(m_pNativeObject, val1, val2, in, output);

}

The C function 'myNativeMethod' is implemented like this:

int myNativeMethod(void* thisInst, int val1, int val2, array<int>^ in,  array<int>^ output)
{
    int n;
    myClass* thisClass = (myClass*) thisInst;

       printf("sample 1: %d \n", val1);
       printf("sample 2: %d \n", val2);
       for (n = 0; n < 10; n++)
       {
          printf("sample %d: %d \n", n, in[n]);
       }

       output[0] = 1024;
       output[1] = 1024;
       output[2] = 1024;
       output[3] = 1024;
       output[9] = 1024;

       return 0;
   }

Upvotes: 0

Views: 80

Answers (1)

Martin Schlott
Martin Schlott

Reputation: 4547

As the comment of xanatos already suggested, your native function/method is not really native as some parameter are still C++/CLI.

If you want to wrap to native C++, I suggest (as I did it myself before):

void ClassProxy::myMethod(int val1, int val2, array<int>^ in, array<int>^ output)
{
    std::vector vin;
    pin_ptr<in> pin(&in[0]);
    int *first(pin), *last(pin + in->Length);
    std::copy(first, last, vin.begin());

     /* Call regular C function */
     std::vector<int> voutput(output->Length);
     m_pNativeObject->myNativeMethod(val1, val2, vin, voutput);

     for(int i=0;i<voutput->size();i++)
       output[i]=voutput[i];
}

Your native method has a signature like:

void myMethod(int val1, int val2, const std::vector<int> &in, std::vector<int> &output);

As your native method is now pure, you can make it part of your native class and call it directly from your wrapper.

Upvotes: 1

Related Questions