I have a function in C++ dll with its return is 2-point, as follows:
#include "stdafx.h"
#include <vector>
using namespace std;
double** _stdcall f(int *n)
{
vector<double> t;
vector<double> X;
int i=0, j=0;
do
{
t.push_back(3*i-4);
X.push_back(2*j);
i++;
j++;
}
while (i<15&&j<90);
*n=i;
double** ret = new double*[2];
for (i=0;i<2;i++)
ret[i]=new double[*n];
for (i=0;i<*n;i++)
{
ret[0][i]=t[i];
ret[1][i]=X[i];
}
return ret;
}
Now, I declare this function in C# as follows:
[DllImport("exDP.dll")]
public static extern IntPtr[2] f(ref int n_);
But there is an error for the syntax of this declaration.
I study as topic: How to get return array from function with global variable from C++ dll in C#?
How to declare correctly with this function? Thanks.
Edit: I fixed the error above, remove "2" (the size of array IntPtr) and it's:
[DllImport("exDP.dll")]
public static extern IntPtr[] f(ref int n_);
Now, all of C# code as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
namespace pABC
{
public partial class frmABC : Form
{
[DllImport("exDP.dll")]
public static extern IntPtr[] f(ref int n_);
public frmABC()
{
InitializeComponent();
}
private void cmdOK_Click(object sender, EventArgs e)
{
int n = 0, i;
IntPtr[] ret = new IntPtr[2];
ret = f(ref n);
double[] t = new double[n];
Marshal.Copy(ret[0], t, 0, n);
double[] X = new double[n];
Marshal.Copy(ret[1], X, 0, n);
MessageBox.Show("X[0]= " + X[0].ToString());
}
}
}
I compile OK. When I run it, an error occurs at the line:
ret = f(ref n);
That is: Cannot marshal 'return value': Invalid managed/unmanaged type combination.
How to fix it and get the results correctly. Thanks.