Andrzej Gis
Andrzej Gis

Reputation: 14306

Pass array from c++ library to a C# program

I'm making a dll in c++ and I want to pass an array to a c# program. I already managed to do this with single variables and structures. Is it possible to pass an array too?

I'm asking because I know arrays are designed in a different way in those two languages and I have no idea how to 'translate' them.

In c++ I do it like that:

extern "C" __declspec(dllexport) int func(){return 1};

And in c# like that:

[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "func")]
public extern static int func();

Upvotes: 0

Views: 421

Answers (3)

C.J.
C.J.

Reputation: 16081

Using C++/CLI would be the best and easier way to do this. If your C array is say of integers, you would do it like this:

#using <System.dll> // optional here, you could also specify this in the project settings.

int _tmain(int argc, _TCHAR* argv[])
{
    const int count = 10;
    int* myInts = new int[count];
    for (int i = 0; i < count; i++)
    {
        myInts[i] = i;
    }
    // using a basic .NET array
    array<int>^ dnInts = gcnew array<int>(count);
    for (int i = 0; i < count; i++)
    {
        dnInts[i] = myInts[i];
    }

    // using a List
    // PreAllocate memory for the list. 
    System::Collections::Generic::List<int> mylist = gcnew System::Collections::Generic::List<int>(count);
    for (int i = 0; i < count; i++)
    {
        mylist.Add( myInts[i] );
    }

    // Otherwise just append as you go... 
    System::Collections::Generic::List<int> anotherlist = gcnew System::Collections::Generic::List<int>();
    for (int i = 0; i < count; i++)
    {
        anotherlist.Add(myInts[i]);
    }

    return 0;
}

Note I had to iteratively copy the contents of the array from the native to the managed container. Then you can use the array or the list however you like in your C# code.

Upvotes: 2

gibraltar
gibraltar

Reputation: 1708

In order to pass the array from C++ to C# use CoTaskMemAlloc family of functions on the C++ side. You can find information about this on http://msdn.microsoft.com/en-us/library/ms692727

I think this will be suffice for your job.

Upvotes: 1

Matěj Z&#225;bsk&#253;
Matěj Z&#225;bsk&#253;

Reputation: 17272

  • You can write simple C++/CLI wrapper for the native C++ library. Tutorial.
  • You could use Platform Invoke. This will definitely be simpler if you have only one array to pass. Doing something more complicated might be impossible though (such as passing nontrivial objects). Documentation.

Upvotes: 1

Related Questions