c#中如何从带有全局变量的c++ dll函数中获取返回数组

How to get return array from function with global variable from C++ dll in C#?

本文关键字:dll c++ 函数 返回 数组 获取 全局变量      更新时间:2023-10-16

我有一个由c++编写的dll文件(文件名为" dll fortest .dll"),这是它的代码:

#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;
}

这是c#代码,从上面的dll文件中调用f函数来获取返回值:

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]);
        }
    }
}

当我运行时,它生成了一个错误:

无法封送"返回值":无效的托管/非托管类型组合。

如何修复它以获得想要的结果?谢谢。

尝试将返回值指定为IntPtr而不是double[],然后使用Marshal.Copy将数据从IntPtr复制到您的double[]数组:

[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]);
}