关于C#调用DLL和C线程回调C#代码问题,大家探讨下。。。。
我使用VC创建了一个DLL文件,这个DLL文件唯一特殊地方是它创建一个线程,该线程可以回调C#代码?
问题出现在回调几次后C#程序出错挂掉。
VC 程序如下:Test.DLL
typedef int(*InputFunction)();
typedef int(*OutputFunction)();
//全局变量
InputFunction SpexInputFunction=NULL;
OutputFunction SpexOutputFunction=NULL;
int IsStop=0;
HANDLE spexthread=NULL;
DWORD spexthreadID;
static DWORD WINAPI ThreadProc(LPVOID lpParam)
{
while(IsStop ==1)
{
Sleep(5000);
SpexInputFunction();
}
SpexOutputFunction();
return 0;
}
//初始化函数指针
int Start(SpeexInputFunction inputfun,SpeexOutputFunction outputfun)
{
SpexInputFunction=inputfun;
SpexOutputFunction=outputfun;
IsStop=1;
spexthread=CreateThread(NULL,NULL,ThreadProc,NULL,0,&spexthreadID);
}
void SpeexNativeStop()
{
IsStop=0;
WaitForSingleObject(spexthread,INFINITE);
CloseHandle(spexthread);
}
C#调用 Start C语言创建一个线程,该线程回调C#中的函数。
C#代码如下:
public delegate int DelegateInput();
public delegate int DelegateOutput();
public partial class Form1 : Form
{
[DllImport("Test.DLL")]
internal static extern int Start(DelegateSpeexInput inputfucntion,DelegateSpeexOutput outputfunction);
[DllImport("Test.DLL")]
internal static extern int Stop();
public static int Input()
{
//MessageBox.Show("InputFunction");
return 0;
}
public static int OutPut()
{
// MessageBox.Show("OutPutFunction");
return 0;
}
private DelegateInput spexinput = new DelegateInput(Input);
private DelegateOutput spexoutput = new DelegateOutput(OutPut);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int result=Start(spexinput, spexoutput);
//MessageBox.Show(result.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
Stop();
}
}
主要代码我已经写出来了,大家一起探讨下。现象是C创建的线程头几次回调是没有问题的,回调次数多了C#主程序就挂掉了。错误提示:中的 0x0365bc00 处未处理的异常: 0xC0000005: 写入位置 0x03770000 时发生访问冲突。