首页 > 解决方案 > 使用 .NET 中的 Dll 的指针参数调用函数

问题描述

我已经使用 C 编写了一个函数并将其构建到一个 DLL 文件中。然后从 C# 中,我像这个示例一样从 Dll 调用我的函数。 https://blogs.msdn.microsoft.com/jonathanswift/2006/10/03/dynamically-calling-an-unmanaged-dll-from-net-c/ 有这样的功能:在C中:

    typedef struct {
        DWORD           Old;                        
    }STRUCT_SON;
    typedef struct {
        DWORD           NumberOfGirl;                   
        STRUCT_SON      SonList[8];
    }STRUCT_PARENT;
    int getStructExample(STRUCT_PARENT* x_lstExample, DWORD* x_dwSum)
    {
    ....
    } 

在 C# 中:

private delegate int getStructExampleDelegate(out ?????,out int iSum);
 IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, 
"getStructExample");
 getStructExampleDelegate getStructExample = 

(getStructExampleDelegate)Marshal.GetDelegateForFunctionPointer(                                                     
                                          pAddressOfFunctionToCall,typeof(getStructExampleDelegate)); 
int iSum;
int theResult = getStructExample(out ??????, out iSum); 

所以我的问题是如何获取结构数据类型?也许使用 Marshal.PtrToStructure。但是什么是“??????” 获取数组 STRUCT_SON。 C# 调用 C++ DLL 函数,它返回一个结构, 我使用这个例子来获取 x_dwSum,但不知道如何获取该结构。

标签: c#cstructdllout

解决方案


???没有出来。它使用 IntPtr 获取结构的地址,然后使用 Marshal.PtrToStructure 解析为 c# 中重新定义的结构。在 C# 中重新定义必须是这样的:

public struct STRUCT_PARENT {
        DWORD           NumberOfGirl;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]                 
        STRUCT_SON[]      SonList;
    };

推荐阅读