【问题标题】:How to get return array from function with global variable from C++ dll in C#?如何从 C# 中的 C++ dll 中的全局变量从函数中获取返回数组?
【发布时间】:2014-08-15 07:43:42
【问题描述】:

我有一个由 C++ 编写的 dll 文件(文件名是“DllForTest.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;
}

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

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

当我运行时,它会产生错误:

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

如何解决它以获得想要的结果?谢谢。

【问题讨论】:

标签: c# c++


【解决方案1】:

尝试将返回值指定为 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]);
}

【讨论】:

  • 现在,我想优化dll文件的C++代码,你对我上面的代码有什么看法?谢谢。
  • @user3479750,好吧,关于上面的代码,我会使用std::copy 而不是for 循环将vret 复制到ret。我也不会使用double 数组来存储ints ;),但我认为这只是一个示例代码,不是吗?当然,您需要一种 Release 方法从 C# 调用以删除分配的 double[] 数组。除此之外,我无法告诉您有关此代码的任何信息,因为它看起来确实是一个简单的示例。
  • 感谢 Alovchin,在您的支持下,我会努力优化我的代码,希望代码变得更好。再次感谢您。
  • 嗨,Alovchin,您能帮我解决link 的错误吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-07-18
  • 2011-06-16
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 2012-04-12
相关资源
最近更新 更多