从非托管 C# DLL 返回列表/数组
Return List/Array from unmanaged C# DLL
我有非托管的C# DLL:
[DllExport(ExportName = "GetStudentsList", CallingConvention = CallingConvention.StdCall)]
static public List<StudentsStruct>GetStudentsList() { return List<StudentsStruct>; }
[DllExport(ExportName = "maxElement", CallingConvention = CallingConvention.StdCall)]
static public int maxElement(int a, int b) { return c; }
我想从函数中返回List<StudentsStruct>
。
我想在C++应用程序中运行上面的函数:
using GetStudentsListFn = List<StudentsStruct> (__stdcall *) (void);
GetStudentsListFn GetStudentsList = reinterpret_cast<GetStudentsListFn> (GetProcAddress(mod, "GetStudentsList"));
List<StudentsStruct> myList = GetStudentsList();
using MaxElementFn = int(__stdcall *) (int a, int b);
MaxElementFn maxElement = reinterpret_cast<MaxElementFn> (GetProcAddress(mod, "maxElement"));
std::printf("max: %dn", maxElement(1, 2));
MaxElement( ( 函数运行良好,因为它返回一个 int。但是我想返回"学生结构"的列表/数组,从C#到C++。
我会使用数组参数out
并返回大小,如下所示:
using ExportDllAttribute.DllExport;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct StudentsStruct
{
public string Name;
public int SomeInt;
public double SomeDouble;
[DllExport]
public static int GetStudentsList([Out] out StudentsStruct[] students)
{
students = new StudentsStruct[] { new StudentsStruct { Name = "Satan", SomeInt = 666, SomeDouble = 666 },
new StudentsStruct { Name = "Techno", SomeInt = 777, SomeDouble = 777 } };
return students.Length;
}
}
和C++代码:
#include<Windows.h>
struct StudentsStruct
{
public:
LPWSTR Name;
int SomeInt;
double SomeDouble;
};
using GetStudentsListFn = int (__stdcall*) (StudentsStruct **);
int main()
{
HMODULE hModule = LoadLibraryA("DllExportArrayTest.dll");
if (hModule)
{
GetStudentsListFn GetStudentsList = reinterpret_cast<GetStudentsListFn>(GetProcAddress(hModule, "GetStudentsList"));
StudentsStruct* students = NULL;
auto size = GetStudentsList(&students);
for (int i = 0; i < size; i++)
auto student = students[i];
FreeLibrary(hModule);
}
}
相关文章:
- C++:如何使函数只返回作为列表一部分的字符串
- 将大括号括起来的初始值设定项列表作为结构返回
- 从封装在对象中的函数 C++ 返回时为空的列表
- 如何在不销毁对象的情况下返回对象列表
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- 给定一个源文件,有没有办法要求 gcc 返回仅直接包含的头文件的列表?
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 从非托管 C# DLL 返回列表/数组
- 在索引中插入节点:链接列表未正确返回列表
- C++列表函数返回列表
- 从 C++ 调用的 python 方法返回列表
- 如何返回列表成员 c++ 的空指针
- std::对中的C++返回列表
- 递归:按顺序遍历返回列表
- 返回列表元素的指针(如果具有相同的名称)
- 如何使用P/Invoke在C#中返回列表
- 当按值返回列表初始化的对象时,为什么不调用复制构造函数?
- 如何在C++中返回列表
- 返回列表前端 (C++) 的类型