这里是我的C代码:保持PInvoked方法活着
LIBRARY_API bool __cdecl Initialize(void (*FirstScanForDevicesDoneFunc)(void));
,这里是C#的PInvoke代码与此DLL工作:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void FirstScanForDevicesDoneFunc();
[DllImport("Native.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern bool Initialize(FirstScanForDevicesDoneFunc);
当我把这种方法是这样的:
static public void Init() {
Initialize(FirstScanForDevicesDone);
}
static public void FirstScanForDevicesDone() {
//do something
}
在结束时Init()回调时我得到NullRefer enceException。所以我用螺纹保持它和一切工作正常,但我不满意这个解决方案:
static public bool Working = true;
static public void Init() {
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
Initialize(FirstScanForDevicesDone);
while (Working)
{
Thread.Sleep(1000);
}
}).Start();
}
有没有一种更复杂的方法来保持这方面的工作?
我们首先需要了解问题。为什么你有'NullReferenceException'?本地代码在做什么?什么时候回叫? – 2014-09-22 11:29:54
为本地代码定义托管回调的标准方法是使用Marshal.GetFunctionPointerForDelegate方法。 – 2014-09-22 11:40:40
@AlexFarber它看起来你以前的评论工作:保持回调函数的静态变量。这意味着回调正在收集。我现在感到很蠢。 – 2014-09-22 11:46:38