开发者

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

开发者 https://www.devze.com 2023-04-06 14:58 出处:网络
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 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();


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号