【问题标题】:Return List/Array from unmanaged C# DLL从非托管 C# DLL 返回列表/数组
【发布时间】:2023-04-02 02:50:01
【问题描述】:

我有非托管 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&lt;StudentsStruct&gt;

我想在 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++。

【问题讨论】:

标签: c# c++ arraylist dll unmanagedexports


【解决方案1】:

我会使用 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);
    }
}

【讨论】:

  • 该技术解决了我的问题,我想知道为什么这个答案有负面评价。有什么更好的方法?
猜你喜欢
  • 1970-01-01
  • 2014-09-14
  • 2013-01-07
  • 2021-05-30
  • 1970-01-01
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多