使用委托和回调函数实现:
C#:
1、创建委托
public delegate void CSharpLogCallback(ref INSTINFO Loginfo);
public CSharpLogCallback cSharpLog;
2、托管
private bool InitlogCallback()
{
cSharpLog = new CSharpLogCallback(Showlogfunction);
return InstrumentAPI.setCPlusLogCallback(Marshal.GetFunctionPointerForDelegate(cSharpLog)) != 0;
}
}
3、Showlogfunction实现
void Showlogfunction(ref INSTINFO Loginfo)
{
if (instModel.enableLog)
{
Loginfo.logdata = Loginfo.logdata.TrimEnd("\n".ToCharArray());
ShowLog(Loginfo.logdata, Convert.ToBoolean(Loginfo.input));
return;
}
else
return;
}
public void ShowLog(object send, bool input)
{
Dispatcher.Invoke(new Action(delegate
{
string strTime = "";
if (input)
{
strTime = "[" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] <<< ";
}
else
{
strTime = "[" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] >>> ";
}
rtbLogPanel.AppendText(strTime + send.ToString() + "\r");
rtbLogPanel.ScrollToEnd();
}));
}
4、C# API接口:
[DllImport("TestSetManage.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "setCPlusLogCallback")]
public static extern int setCPlusLogCallback(IntPtr logCallback);
C++
1、定义函数指针:
typedef void(*CPPLogCallback)(INSTINFO& info);
2、定义接口并实现接口:
TestSetControl_API void __cdecl setCPlusLogCallback(CPPLogCallback logcb);
void __cdecl setCPlusLogCallback(CPPLogCallback logcb)
{
pTestSetCtrl->comfun.logcallbackptr = logcb;
return;
}
至此,在类的实例comfun中C#的logcallbackptr已接收到C#传下来的函数指针,可直接使用,
使用如下:
bool CommonFunc::AddToLog(char* cmdstr,int type)
{
INSTINFO instinfo;
memcpy(instinfo.logdata, "", sizeof instinfo.logdata);
strcat(instinfo.logdata, cmdstr);
instinfo.input = type;
logcallbackptr(instinfo);
return true;
}
以上学习过程记录,仅展示了关键代码。