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

1 Answer 1

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]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Now, I want to optimize C++ code of dll file, what is your opinion about my code above? Thanks.
@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 ints ;), 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.
Thanks Alovchin, I will try to optimize my code with your support, hope that code become better. Thank you a lot again.
Hi Alovchin, can you help me fix errors at link. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.