I ended up using Danvil . I wrapped the C code in a C ++ dll, and then created another C # dll that referenced the C ++ dll and revealed the functionality I wanted in managed code. So here it is:
C ++ dll:
.h file
typedef void (*FncDlg) (const unsigned char*, int len);
extern "C" __declspec(dllexport) void AttachCallback(FncDlg f);
void PassData(const unsigned char *Body, int BodyLen);
.cpp file
void (*callback)(const unsigned char*, int len) = 0;
void AttachCallback(FncDlg f)
{
callback = f;
}
void PassData(const unsigned char *Body, int BodyLen)
{
if(callback) {
callback(Body, BodyLen);
}
}
C # dll:
public static class Parser
{
public delegate void DlgDumpTipData(IntPtr a, int len);
[DllImport("C++ dll name here", EntryPoint = "AttachCallback", ExactSpelling = true)]
public static extern void AttachCallback(DlgDumpTipData callback);
public static int ConnectAndStartReceive(...)
{
AttachCallback(DumpDataCalback);
...
}
public delegate void MsgHandler(string msg);
public static event MsgHandler OnMessageArrived = delegate { };
public static void DumpDataCalback(IntPtr ptr, int len)
{
string dumpData;
sbyte[] byteArr = new sbyte[len];
for (int i = 0; i < len; i++)
{
byteArr[i] = (sbyte)Marshal.ReadByte(ptr, i);
}
unsafe
{
fixed (sbyte* pbyteArr = byteArr)
{
dumpData = new String(pbyteArr, 0, len, Encoding.GetEncoding("ISO-8859-1"));
}
}
OnMessageArrived(dumpData);
GC.Collect();
}
}
tzup source
share