简体   繁体   中英

How to transmit c++ strucure from dll to c# program?

I have DLL, written in C++. There is structure in this DLL.

typedef struct TransmitData
{
wchar_t    szPath[MAX_PATH];
DWORD      dwResult;
} *lpTransmitData;

And I have one function to fill this struct

extern "C" __declspec(dllexport) int GetData(struct TransmitData &data)
{
//I HAVE ONE THE SAME STRUCT IN THIS DLL
memcpy(&data, &transmitData, sizeof(struct TransmitData));
return ret_value;
}

In C# program I use functions with simple data types well, but for structure it doesn't work. There is code on C#:

public struct TransmitData
{
[MarshalAs(UnmanagedType.LPWStr, SizeConst = 260)] //260 = MAX_PATH
public string szPath;
public uint dwResult;
}
//...
[DllImport("MyDLL")]
public static extern int GetData(ref TransmitData data);

What am I doing wrong? Thanks!

I suggest you to replace

[DllImport("MyDLL")]

with

[DllImport("MyDLL", CallingConvention = CallingConvention.Cdecl)]

and

extert "C"

with

extern "C"

Moreover, as Joe suggested, add

[StructLayout(LayoutKind.Sequential)]

before the declaration of the struct in C# code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM