2
votes

I have a dll file which is written by C++ (the name of file is "DllForTest.dll"), this is its code:

#include "stdafx.h"
#include <vector>
using namespace std;

double *ret;
double* _stdcall f(int* n)
{
    vector<double> vret;
    int i=0;
    do
    {
        vret.push_back(i);
        i++;
    } while (the condition to stop this loop);
    *n=i;
    ret = new double[*n];
    for (i=0;i<*n;i++)
        ret[i]=vret[i];
    return ret;
}

This is C# code to call f function from the dll file above to get return value:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowForm
{
    public partial class Form1 : Form
    {
        [DllImport("DllForTest.dll")]
        public static extern double[] f(ref int n);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int n=0;
            double[] x;
            x = f(ref n);
            MessageBox.Show("x[0]= " + x[0]);
        }
    }
}

When I run, it generate an error:

Cannot marshal 'return value': Invalid managed/unmanaged type combination.

How to fix it to gain wanted result? Thanks.

1

1 Answers

2
votes

Try specifying return value as IntPtr instead of double[] and then use Marshal.Copy to copy data from this IntPtr to your double[] array:

[DllImport("DllForTest.dll")]
static extern IntPtr f(ref int n);

private void button1_Click(object sender, EventArgs e)
{
    int n=0;

    IntPtr intPtr = f(ref n);
    double[] x = new double[n];
    Marshal.Copy(intPtr, x, 0, n);

    MessageBox.Show("x[0]= " + x[0]);
}