2

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 Answers1

2

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]);
}
Alovchin
  • 663
  • 3
  • 9
  • Now, I want to optimize C++ code of dll file, what is your opinion about my code above? Thanks. – Newton Isaac Aug 15 '14 at 08:19
  • @user3479750, well, regarding the code above, I would use `std::copy` instead of `for` loop to copy `vret` to `ret`. I also wouldn't use the `double` array to store `int`s ;), but I think it's just an example code, isn't it? And of course you'll need a kind of `Release` method to call from C# to remove the allocated `double[]` array. Other than that, I can't tell you anything about this code since it really seems to be an easy example. – Alovchin Aug 15 '14 at 09:24
  • Thanks Alovchin, I will try to optimize my code with your support, hope that code become better. Thank you a lot again. – Newton Isaac Aug 15 '14 at 12:20
  • Hi Alovchin, can you help me fix errors at [link](http://stackoverflow.com/questions/25341441/declare-function-which-its-return-is-2-point-from-c-dll-in-c). Thanks. – Newton Isaac Aug 17 '14 at 13:03