gpt4 book ai didi

c# - 从非托管 C# DLL 返回列表/数组

转载 作者:行者123 更新时间:2023-11-28 04:03:42 26 4
gpt4 key购买 nike

我有非托管 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: %d\n", maxElement(1, 2));

MaxElement( ) 函数运行良好,因为它返回一个 int。但我想将“StudentsStruct”的列表/数组从 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# DLL 返回列表/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59092978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com