c#中如何从带有全局变量的c++ dll函数中获取返回数组
How to get return array from function with global variable from C++ dll in C#?
我有一个由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]);
}
相关文章:
- 挂起和取消挂起一个文件DLL
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 导入库可以跨dll版本工作吗
- 从C++dll访问C#中的一行主要参数
- 链接到自行创建的dll失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- C++:将外部库链接到dll库
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 不同的Visual Studio版本中缺少.dll
- 从DLL中删除类的实例
- 如何包装第三方DLL在R中使用
- 使用c#访问c++dll中带有char*参数的函数时发生AccessViolationException
- 系统.将数组移交给c#中动态加载的c++DLL时发生AccessViolationException
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Python ctypes:不会按预期加载 dll
- 在 C++/CLI 中将 .NET 事件从一个 DLL 引发到另一个 DLL