0

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();
0

3 Answers 3

2

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.

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

Comments

1
  • 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.

Comments

1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.