简体   繁体   中英

Passing a C++ array to a C# function

I am trying to use C# libraries to easily convert a raw pixel array to a PNG file. I wrote my initial program using C++ and OpenGL, so the best approach was to pass my C++ pixel array to C# dll using COM and make C# dll save them as a PNG file. I can easily pass values into C# but I can't figure out quickly how to pass an unmanaged C++ array to C#. I have read you can use SAFEARRAYS or do some sort of Marshaling and Unmarshaling. Anyways I am not sure about them. Here's my C# code,

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace PNG_Creator_DLL
{
[ComVisible(true)]
public interface IPicturesAndMovies
{
    //int Add(int a, int b);
    int CreatePNG(UInt16[] imagery_data);
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class PNG_Create_Class: IPicturesAndMovies
{
    public int CreatePNG(UInt16[] imagery_data)
    {


        //create the images directory
        Directory.CreateDirectory("images");

        String fileName = "images\\PNG_test_nmr" + "_0000.png";
        var pngStream = new FileStream(fileName, FileMode.Create);

        readImage(imagery_data, pngStream, 384, 288);  //create the png frame
        pngStream.Close();
        fileName = "images\\PNG_test_nmr" + "_" + "0001" + ".png";
        pngStream = new FileStream(fileName, FileMode.Create);

        pngStream.Close();
        File.Delete(fileName);


        return 0;
    }

    private Boolean readImage(UInt16[] imagery_data, Stream pngStream, Int32 width, Int32 height)
    {


        var bmp = new WriteableBitmap(width, height, 96, 96, PixelFormats.Gray16, null);
        Int32 bytesPerPixel = bmp.Format.BitsPerPixel / 8;
        Int32Rect drawRegionRect = new Int32Rect(0, 0, bmp.PixelWidth, bmp.PixelHeight);


        Int32 stride = bmp.PixelWidth * bytesPerPixel;
        bmp.WritePixels(drawRegionRect, imagery_data, stride, 0);

        PngBitmapEncoder enc = new PngBitmapEncoder();
        enc.Frames.Add(BitmapFrame.Create(bmp));
        enc.Save(pngStream);

        return true;
    }
 }
}

Here's my C++ code that uses COM and tries to pass the array to C# dll

#include "stdafx.h"
#include <Windows.h>
#import "..\x64\Release\dllFiles\PNG_Creator_DLL.tlb" no_namespace

int main()
{
unsigned short* imagery_data = new unsigned short[384 * 288];
unsigned short temp_sum = 0;
for (int index_row = 0; index_row < 288; index_row++)
{
    temp_sum = 0;
    for (int index_col = 0; index_col < 384; index_col++)
    {

        imagery_data[index_row * 384 + index_col] = temp_sum;
        temp_sum = (unsigned short)(temp_sum + 160);
    }
}

CoInitialize(NULL);

IPicturesAndMoviesPtr obj;
obj.CreateInstance(__uuidof(PNG_Create_Class));
printf("Create      = %d\n", obj->CreatePNG(imagery_data));

CoUninitialize();
return 0;
}

I get an C2664 compiler error at printf("Create = %d\\n", obj->CreatePNG(imagery_data));

It says 'long IPicturesAndMovies::CreatePNG(SAFEARRAY *)': cannot convert argument 1 from 'unsigned short *' to 'SAFEARRAY *'

Any ideas on how to fix it?

Try as said below. It may work

//YOUR ARRAY NEEDS TO BE CONVERTED TO SAFE ARRAY
unsigned short* imagery_data = new unsigned short[384 * 288];

//DECLARE A SAFE ARRAY POINTER
SAFEARRAY *psa;  


//AS THE REQUIRED IS UInt16[] - USE VT_UI2 
//LOWER BOUND  = 0
//UPPER BOUND = 110592 (384 * 288)
psa = SafeArrayCreateVector(VT_UI2, 0, 110592);  //REFER DOCUMENTATION

unsigned short *pData;  
HRESULT hr = SafeArrayAccessData(psa, (void **)&pData); //REFER DOCUMENTATION
memcpy(pData, imagery_data, 110592*sizeof(unsigned short));  
SafeArrayUnaccessData(psa);//REFER DOCUMENTATION

And then use psa to pass.

After you are done with usage call SafeArrayDestroy to clean up.

SafeArrayDestroy(psa);

The above code is lifted from below link and shortened.

https://github.com/MicrosoftDocs/cpp-docs/blob/master/docs/dotnet/how-to-marshal-a-safearray-for-adonet-cpp-cli.md

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