Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

c++ - How to Pass address of Stucture to Void pointer[void*] in C# to VC++ Dll

//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("
 mydata
 %s ", mydata->call); 
printf("
 mydata
 %s ", mydata->summary); 
printf("
 mydata
 %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...!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...