'heap corrupt when convert Intptr in C# to char* in C++ DLL
I'm trying to convert an array to DLL and modify the values in it.It goes well and the values in array changed.But the problem is,it cause a heap corruption that sometimes it thows out an AccessViolationException,other times the program crash at random
function in DLL code in C++:
MCUPROTOCOL_API int funMcuReadEEprom(const char bank, unsigned char page, char* EEprom,int DataSize)
{
st_PROTOCOL stResponsePackage;
RS232_AT_COMMAND Command;
memset(Command.szCommand, 0x00, sizeof(Command.szCommand));
unsigned char Package[8] = { 0x00 };
unsigned char ResponsePackage[32] = { 0x00 };
unsigned char Data[2] = { 0x00 };
int State;
int ResponsePackageLen;
Data[0] = bank;
Data[1] = page;
fun_ProducePackage(TEST_READ_SOFTWARE_VERSION, Data, Package);
memcpy(Command.szCommand, Package, sizeof(Package));
Command.dwLength = sizeof(Package);
Uart.WriteByte(Command);
Sleep(200);
State = Uart.ReadByte((char *)ResponsePackage, &ResponsePackageLen);
if (ERROR_SUCCESS != State)
{
return FAIL_UART;
}
State = fun_AnalyzeResponsePackage(ResponsePackageLen, ResponsePackage, &stResponsePackage);
if (ERROR_SUCCESS != State)
{
return State;
}
//memcpy(EEprom, stResponsePackage.data, DataSize);
return SUCCESS;
}
C#:
[DllImport("McuProtocol.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int funMcuReadEEprom(byte bank, byte page, IntPtr EEprom, int DataSize);
and I call it like this:
byte page = 129;
byte bank = 2;
string TransferStr = "";
IntPtr SoftwareVersion;
byte[] transfer = new byte[20];
SoftwareVersion = Marshal.StringToCoTaskMemAuto(TransferStr);
McuProtocolApi.funMcuRegister(int.Parse(Info.UartCom.Substring(3)), int.Parse(Info.UartBaud));
McuProtocolApi.funMcuReadEEprom(bank, page, SoftwareVersion, SoftwareVersionSize);
McuProtocolApi.funMcuRelease();
transfer = System.Text.Encoding.Unicode.GetBytes(Marshal.PtrToStringAuto(SoftwareVersion, SoftwareVersionSize / 2));
TransferStr = System.Text.Encoding.UTF8.GetString(transfer);
StrSW = TransferStr;
If I annotate funMcuReadEEprom ,the program went well,otherwise,when it reach this line,the Program would crash.
EDIT 1: I optimized the code by the suggestions in the comment and the problem still exist.
byte page = 128;
byte bank = 2;
string TransferStr;
IntPtr SoftwareVersion = Marshal.AllocHGlobal(100);
byte[] transfer = new byte[20];
McuProtocolApi.funMcuRegister(int.Parse(Info.UartCom.Substring(3)), int.Parse(Info.UartBaud));
McuProtocolApi.funMcuReadEEprom(bank, page, SoftwareVersion, SoftwareVersionSize);
McuProtocolApi.funMcuRelease();
transfer = System.Text.Encoding.Unicode.GetBytes(Marshal.PtrToStringAuto(SoftwareVersion, SoftwareVersionSize / 2));
TransferStr = System.Text.Encoding.UTF8.GetString(transfer);
StrSW = TransferStr;
Marshal.FreeHGlobal(SoftwareVersion);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
