如何从功能和全局变量从C ++ DLL在C#中返回数组? [英] How to get return array from function with global variable from C++ dll in C#?
本文介绍了如何从功能和全局变量从C ++ DLL在C#中返回数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个用C编写的dll文件++(文件名是DllForTest.dll),这是它的代码:
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;
}
这是C#代码来调用f函数从DLL文件上面得到回报值:
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.
推荐答案
尝试指定返回值的IntPtr
而不是<$的C $ C>双[] ,然后用 Marshal.Copy
从这个IntPtr的数据复制到你的双[]数组:
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]);
}
这篇关于如何从功能和全局变量从C ++ DLL在C#中返回数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文