I wrote some testcase named LibTest.dll (act like strcpy) in VC++ 6.0
LibTest.h shown as below:
#define DLLEXPORT extern "C" __declspec(dllexport)
DLLEXPORT void LibTestInit();
DLLEXPORT void LibTestStrCpy(char *in, char *out);
DLLEXPORT void LibTestCleanup();
LibTest.cpp shown as below:
#include "LibTest.h"
#include <stdio.h>
namespace CCTEC
{
class Test
{
public:
Test() {}
~Test() {}
public:
void strcpy(char *in, char *out)
{
while (*out++ = *in++);
}
};
};
static CCTEC::Test *m_Test = NULL;
DLLEXPORT void LibTestInit()
{
m_Test = new CCTEC::Test();
}
DLLEXPORT void LibTestCleanup()
{
if (m_Test) delete m_Test; m_Test = NULL;
}
DLLEXPORT void LibTestStrCpy(char *in, char *out)
{
if (m_Test) m_Test->strcpy(in, out);
}</stdio.h>
Then using DllImport to call unmanaged functions (such as LibTestInit )
that are implemented in a DLL (LibTest.dll)
LibTest.cs (part of the source code) shown as below:
using System.Runtime.InteropServices;
public class LibTest
{
#region DLL Import
[DllImport("LibTest")]
private static extern void LibTestInit();
[DllImport("LibTest")]
private static extern void LibTestCleanup();
[DllImport("LibTest")]
private static extern void LibTestStrCpy(byte[] inStr, byte[] outStr);
#endregion
public LibTest()
{
LibTestInit();
}
public void Dispose()
{
LibTestCleanup();
}
public void StrCpy(byte[] inStr, byte[] outStr)
{
LibTestStrCpy(inStr, outStr);
}
}
And Form1.cs (with a TextBox control to test the output) shown as below:
m_LibTest1 = new LibTest();
byte[] outStr1 = new byte[1024];
m_LibTest1.StrCpy(System.Text.Encoding.Default.GetBytes("Hello World"), outStr1);
m_LibTest1.Dispose();
m_LibTest1 = null;
textBox.Text += System.Text.Encoding.Default.GetString(outStr1);
MessageBox.Show(System.Text.Encoding.Default.GetString(outStr1));
m_LibTest2 = new LibTest();
byte[] outStr2 = new byte[1024];
m_LibTest2.StrCpy(System.Text.Encoding.Default.GetBytes("Hello Linux"), outStr2);
m_LibTest2.Dispose();
m_LibTest2 = null;
textBox.Text += System.Text.Encoding.Default.GetString(outStr2);
MessageBox.Show(System.Text.Encoding.Default.GetString(outStr2));
Expected output: Hello WorldHello Linux
Actual output: Hello World
So Who Moved My "Hello Linux" byte[] ?
Please someone catched the thief who moved my byte[], thanks a lot!