這裏是我的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