C dll触发事件 [英] fire event from C dll
问题描述
我使用C编程语言和Visual Studio创建了一个dll,它在C#.net中使用,在我的应用程序中可以正常工作.现在,我需要从C编码的dll中触发一个事件,如何使用C编码创建一个事件,以及如何从其他语言调用该事件,并且我的dll不是COM组件,所以我需要从我的c dll,我正在使用[DllImport(...)]调用c dll方法.在您的C dll中创建一个函数,该函数在初始化时调用.它的参数之一是指向函数的指针.
在您的C#代码中,您调用该初始化函数并移交委托(可能需要一些 ^ ]知识).该委托指向触发您想要的事件的函数.
在C语言中,当您要触发事件时,可以调用初始化时提供的回调函数.
C世界中的事件"通常是通过函数指针完成的,也就是说,您将函数指针传递给启动任务的函数,任务完成时将调用该函数指针.
// C declaration extern int start_something(void (*f)()) { // do some stuff ... (*f)(); // call back to the outside }
有时,函数指针存储在结构中或向单个函数注册,然后用于响应其他函数,但是思想是相同的.
通过P/Invoke,您可以将委托传递给具有这种签名类型的函数,即
[DllImport(...)] public int start_something(VoidDelegate f); public delegate void VoidDelegate();
(很抱歉,如果我忘记了如何在C中编写函数指针,那已经很长时间了:P.)
更新的C示例
I created one dll using C programming language and visual studio, Its using in C#.net its working fine in my application. Now I need to fire an event from my C coded dll, How I can create an event in C coding and how I can call it from other language and my dll is not a COM component, I need to call one of the C# function from my c dll, I am using [DllImport(...)] to invoke c dll methods
It''s not an event as such, but you can create a function in your C dll, that is called on initialization. One of its parameters is a pointer to a function.
In your C# code, you call that initialization function and hand over a delegate (may require some marshalling[^] knowledge). That delegate points to a function that fires your desired event.
In C, when you want the event to fire, you call the callback function you were given on initialization.
''Events'' in the C world tend to be done through function pointers, i.e. you pass a function pointer to the function that starts a task, and it will be called when the task is complete.
// C declaration extern int start_something(void (*f)()) { // do some stuff ... (*f)(); // call back to the outside }
Sometimes the function pointer is stored in a structure or registered with a single function and then used in response to others, but the idea is the same.
Through P/Invoke you can pass a delegate to functions with this type of signature, i.e.
[DllImport(...)] public int start_something(VoidDelegate f); public delegate void VoidDelegate();
(Apologies if I forgot how to write function pointers in C, it''s been a long, long time :P.)
edit: updated C sample
这篇关于C dll触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!