How to Pass address of Stucture to Void pointer[vo

2019-09-19 17:35发布

//Structure:

struct MYDATA{
char calls[4069];      
char Desc[4096];   
char error[1024];     

} ;

//Test function

char *Argv[] = { "ToolName", "USername", "192.168.2", "3", "400"};  
typedef void* ( *__stdcall  pCstartSIPSessionint)(char **argv ); 
typedef struct MYDATA*(*__cdecl pgetStat) ();

pCstartSIPSessionint startSessionint = (pCstartSIPSessionint )GetProcAddress(HMODULE (hGetProcIDDLL),"startSessionint"); 

//Dll Import

HINSTANCE hGetProcIDDLL = LoadLibrary(TEXT("E:\\MyDll.dll"));

pgetStat getStat ;
getStat = (pgetStat ) startSessionint(Argv);

MYDATA *mydata;
if(getStat != NULL)
        mydata= getStat();
printf("\n mydata\n %s ", mydata->call); 
printf("\n mydata\n %s ", mydata->summary); 
printf("\n mydata\n %s ", mydata->error);

How to Convert the code in C#? And i have confused to pass address of stucture to Void* in C# I can able to pass only values, how can pass Address to the structure.

Thanks in advance...!

标签: c# c++ pinvoke
1条回答
别忘想泡老子
2楼-- · 2019-09-19 17:56

The struct should be:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MYDATA
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4096)]
    public string calls;      
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4096)]
    public string Desc;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
    public string error;     
}

I assume the 4069 value in the question is a typo.

The first function is:

[DllImport(dllname, CharSet = CharSet.Ansi)] 
public static extern IntPtr startSessionint(string[] argv);

Then convert the function pointer to a delegate:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate IntPtr getStatDelegate();
....
IntPtr ptr = startSessionint(argv);
if (ptr == IntPtr.Zero)
    // handle error
getStatDelegate getStat = (getStatDelegate)Marshal.GetDelegateForFunctionPointer(ptr, typeof(getStatDelegate));

Now you can call the function:

IntPtr structPtr = getStat();

And then marshal to the struct:

MYDATA data = (MYDATA)Marshal.PtrToStructure(structPtr, typeof(MYDATA));
查看更多
登录 后发表回答