简体   繁体   中英

Marshaling a return array from C++ to C#

I have a array in my C++ app and I want to use it's pointer to create a C# array delegate from it without copying. So I could make it work from C# to C++ , C++ access the same array defined in C# but cannot make it work in reverse.

C# Code :

   [DllImport("CppDll.dll",CallingConvention=CallingConvention.Cdecl)]
   [return: MarshalAs(UnmanagedType.LPArray)]
   public static extern int[] GetCppArray();

C++ Code :

    int test_data[5] = { 12,60,55,49,26 };

    extern "C" __declspec(dllexport) int* GetCppArray()
    {
        return test_data;
    }

Using in C# :

int[] cpparray = NativeLib.GetCppArray();

And I get this error :

System.Runtime.InteropServices.MarshalDirectiveException: 'Cannot marshal 'return value': Invalid managed/unmanaged type combination.'

I know I can use memory writers to write directly to C++ memory with array pointer address. It works if use the same MarshalAs(UnmanagedType.LPArray) in parameter and pass a C# array to c++ but why it doesn't work in opposite action?

Note : My data is huge I really can't use any copy here.

You should read this article fully first: https://docs.microsoft.com/en-us/dotnet/framework/interop/default-marshaling-for-arrays#unmanaged-arrays

I also found this relevant QAs: How to create and initialize SAFEARRAY of doubles in C++ to pass to C#

Your GetCppArray function only returns a pointer - it doesn't return a self-describing "safe" array, whereas arrays in .NET include length and rank (dimension) information, so you definitely need to modify the C++ code to do this correctly.

The first option is to return the array as a COM-style safe array , this is done with the SAFEARRAY( typename ) macro - and it must be passed as a parameter, not a return value.

There are two main ways of using COM Safe-Arrays in C++: using the Win32 functions like SafeArrayCreate - which are painful to use correctly, or by using the ATL CComSafeArray .

(Disclaimer: I wrote this code by looking at the API references, I haven't tested it - I don't even know if it will compile).

// C++ code for SafeArrayCreate:

#include <comdef.h>
int test_data[5] = { 12, 60, 55, 49, 26 };

extern "C" __declspec(dllexport) HRESULT GetCppArray( [out] SAFEARRAY( int )** arr )
{
    SAFEARRAYBOUND bounds;
    bounds.lLbound   = 0;
    bounds.cElements = sizeof(test_data);

    *arr = SafeArrayCreate(
        VT_I4,  // element type
        1,      // dimensions
        &bounds 
    );
    if( !arr ) {
        // SafeArrayCreate failed.
        return E_UNEXPECTED;
    }

    int* arrPtr;
    HRESULT hr = SafeArrayAccessData( *arr, &arrPtr );
    if( !SUCCEEDED( hr ) ) {
         hr = SafeArrayDestroy( arr );
         // After SafeArrayDestory, if `hr != S_OK` then something is really wrong.
         return E_UNEXPECTED;
    }

    for( size_t i = 0; i < sizeof(test_data); i++ ) {
        *arrPtr[i] = test_data[i];
    }

    hr = SafeArrayUnaccessData( *arrPtr );
    if( !SUCCEEDED( hr ) ) {
         hr = SafeArrayDestroy( arr );
         return E_UNEXPECTED;
    }

    return S_OK;
}

The C# code then needs to be updated to declare it returns a SafeArray :

// HRESULT is best represented as a UInt32 instead of Int32.

[DllImport( "CppDll.dll", CallingConvention = CallingConvention.Cdecl )]
public static extern UInt32 GetCppArray(
    [MarshalAs( UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_I4 )] out Int32[] arr
);

Maybe you can use Marshal.ReadInt32() to process your data?

[DllImport("CppDll.dll",CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr GetCppArray();

var cpparray = NativeLib.GetCppArray();
var test_data_2 = Marshal.ReadInt32(cpparray, 2 * sizeof(int));
Console.WriteLine(test_data_2); // 55

It looks like Span<T> might be pretty close to what you want; there is a sample that's pretty-much spot-on, although it does still require unsafe .

 Span<int> cpparray;
 unsafe
 {
     cpparray = new Span<int>((int*)NativeLib.GetCppArray(), 5);
 } 
 Console.WriteLine(cpparray[2]); // 55

I modified my original answer by proposing you to use C++/CLI . You said that you use .NET Framework , so C++/CLI is a good option. By using it you don't need to copy for C++ pointer. Just create a C++/CLI wrapper class over your C++ pointer. Below is an example.

C++ code

functions.h

#pragma once
#ifdef LIBRARY_EXPORTS
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif

#ifdef __cplusplus
extern "C"
{
#endif

    API int* GetCppArray();
    API int GetCppArraySize();
    API void DeleteCppArray(int* vec);

#ifdef __cplusplus
}
#endif

functions.cpp

#include "pch.h"
#include "functions.h"

const int vecSize = 10000;

int* GetCppArray()
{
    int* vec = new int[vecSize];
    for (int i = 0; i < vecSize; ++i)
    {
        vec[i] = i * 2;
    }

    return vec;
}

int GetCppArraySize()
{
    return vecSize;
}

void DeleteCppArray(int* vec)
{
    delete[] vec;
}

C++/CLI code

Wrapper.h

#pragma once

using namespace System;

namespace Wrapper 
{
    public ref class ArrayWrapper : public IDisposable
    {
    private:
        int* values;
        int size;
        bool isDisposed;

    public:
        ArrayWrapper();
        ~ArrayWrapper();
        !ArrayWrapper();

        property int Size
        {
            int get();
        }

        property int default[int]
        {
            int get(int index);
            void set(int index, int value);
        }
    };
}

Wrapper.cpp

#include "pch.h"
#include "Wrapper.h"

#include "../Library/functions.h"

namespace Wrapper
{
    ArrayWrapper::ArrayWrapper()
    {
        this->values = GetCppArray();
        this->size = GetCppArraySize();
        this->isDisposed = false;
    }

    ArrayWrapper::~ArrayWrapper()
    {
        if (this->isDisposed == true)
        {
            return;
        }

        this->!ArrayWrapper();
        this->isDisposed = true;
    }

    ArrayWrapper::!ArrayWrapper()
    {
        DeleteCppArray(this->values);
        this->values = nullptr;
        this->size = 0;
    }

    int ArrayWrapper::Size::get()
    {
        return this->size;
    }

    int ArrayWrapper::default::get(int index)
    {
        if (index < 0 || index >= this->size)
        {
            throw  gcnew Exception("Invalid index");
        }
        return this->values[index];
    }

    void ArrayWrapper::default::set(int index, int value)
    {
        if (index < 0 || index >= this->size)
        {
            throw  gcnew Exception("Invalid index");
        }

        this->values[index] = value;
    }
}

C# code

using System;
using Wrapper;

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayWrapper vector = new ArrayWrapper();

            for (int i = 0; i < vector.Size; i++)
            {
                Console.Write($"{vector[i].ToString()} ");
            }
            Console.WriteLine();
            Console.WriteLine("Done");

            int index = vector.Size / 2;
            Console.WriteLine($"vector[{index.ToString()}]={vector[index].ToString()}");
            vector[index] *= 2;
            Console.WriteLine($"vector[{index.ToString()}]={vector[index].ToString()}");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM