Robin Rodricks
Robin Rodricks

Reputation: 113976

Convert a List to an unmanaged array for C++/CLI

I'm creating a .NET wrapper class to a C++/CLI function. Internally the function uses an array of ints (int*), but I'd like to expose a clean List<int>^ on the .NET side. I'm using the following code to convert a C# List to a C++ unmanaged list of int.

Apart from the fact that I'm not freeing the allocated memory using Marshal::FreeHGlobal, is there any problem with the function? For example, should I be allocating ((count * 4) + 4) for the array length bytes?

static int* ListToArray(List<int>^ list){

    // new array
    int count = list->Count;
    int* arr = (int*)(Marshal::AllocHGlobal(count * 4).ToPointer());

    // convert list to array
    for(int a = 0; a < count; a++){
        arr[a] = list[a];
    }
    return arr;
}

Upvotes: 0

Views: 3152

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

Your code is correct. You allocate the correct amount of memory. Instead of 4 I would use sizeof int, which is more expressive.

I do wonder why you are using AllocHGlobal. I think new would be more appropriate in C++ code. And I also wonder why you are using raw pointers. Wouldn't std::vector<int> makes more sense in C++ code?

Upvotes: 2

Related Questions