Search code examples
c#cstructdllout

Calling the function using pointer parameter of Dll from .NET


I have written a function using C and built it into a DLL file. Then from C#, I call my function from Dll like this sample. https://blogs.msdn.microsoft.com/jonathanswift/2006/10/03/dynamically-calling-an-unmanaged-dll-from-net-c/ There is a function like that: In 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)
    {
    ....
    } 

In 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); 

So my question is How to get the struct data type? Maybe using Marshal.PtrToStructure. But What is "????" to get array STRUCT_SON. C# Calling C++ DLL Function which returns a struct Im using like this example to get x_dwSum, but dont know to to get that struct.


Solution

  • ???? is not out. Its using IntPtr to get address of struct then using Marshal.PtrToStructure to Parse into redefined struct in c#. redefine in C# must be like this:

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