次のような状況があります: シリアル ポート経由で I/O デバイスと「対話」する C++ ライブラリ。C++ ライブラリはデバイスでいくつかのポーリングを行い、入力が設定されるとコールバック関数が呼び出されます。
#if defined( _MSC_VER ) || defined( __MINGW32__ ) || defined( __MINGW64__ )
# define LIB_CALLBACK __stdcall
# define LIB_CALL __cdecl
# if defined( LIB_EXPORTS )
# define LIB_API __declspec( dllexport )
# else
# define LIB_API __declspec( dllimport )
# endif
#else
# define LIB_API
#endif // WIN32
#if defined( __cplusplus )
extern "C" {
#endif
typedef int libInput;
typedef void (* LIB_CALLBACK libOnInput ) ( libInput buttons );
LIB_API void LIB_CALL libRegisterInput( libInput f );
#if defined( __cplusplus )
}
#endif
これがスレッド機能です
libOnInput g_libOnInputFunc = nullptr;
LIB_API void LIB_CALL libRegisterInput( libInput f )
{
libOnInputFunc = f;
}
// while true
if ( g_iocOnInputFunc )
{
libInput = // ...
// the event is called asyncronously. I don't want block the current thread
std::thread t( g_libOnInputFunc, in );
t.detach();
}
現在、このライブラリは VB.net アプリケーションから使用する必要があります。ライブラリを C# でラップしました
public delegate void OnInputDownDelegate(int input);
[DllImport("mylib.dll", CallingConvention = CallingConvention.Cdecl)]
internal static extern void libRegisterInput( OnInputDownDelegate f );
public void RegisterOnInput(OnButtonDownDel f)
{
libRegisterInput(f);
}
Visual Basic では、C# ラッパー ライブラリを直接使用します。
Imports CSharpLib
Public Class Form1
Private Shared myLib As CSharpLib.CSharpLib
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
myLib = New CSharpLib.CSharpLib()
myLib.RegisterOnButtonDown(New CSharpLib.OnInputDownDelegate(AddressOf OnInput))
End Sub
Private Sub OnInput(ByVal input As Integer)
MessageBox.Show(input.ToString())
End Sub
End Class
しかし、デバイスのボタンを押してアプリケーションを実行すると、mylib.dll が入力をキャッチし、コールバック関数を呼び出そうとしますが、アプリケーションがクラッシュします。null 参照でデリゲートを呼び出しているようです。
これはエラーコードです:
Eccezione non gestita di tipo 'System.NullReferenceException' in Modulo sconosciuto.
Informazioni aggiuntive: Riferimento a un oggetto non impostato su un'istanza di oggetto.
翻訳は次のとおりです。
Exception of type 'System.NullReferenceException' in Unknown Module
Extra information: Reference to an object not setted on an object instance