如何将结构地址传递给Void指针[void *]到VC ++ Dll中

时间:2014-08-04 04:47:22

标签: c# c++ pinvoke

//结构:

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

} ;

//测试功能

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

如何在C#中转换代码? 我很困惑,在C#中将结构地址传递给Void * 我只能传递值,如何将Address传递给结构。

提前致谢...!

1 个答案:

答案 0 :(得分:0)

结构应该是:

[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;     
}

我认为问题中的4069值是一个错字。

第一个功能是:

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

然后将函数指针转换为委托:

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

现在您可以调用该函数:

IntPtr structPtr = getStat();

然后编组到结构:

MYDATA data = (MYDATA)Marshal.PtrToStructure(structPtr, typeof(MYDATA));