挂钩到C#DLL事件表C#

时间:2013-05-08 10:27:06

标签: c# c++ events dll

我想将C#方法挂钩到用C ++ DLL编写的C ++事件

C ++方面     #include

extern "C"
{
    typedef void (__stdcall *PFN_MYCALLBACK)();
    int __stdcall MyUnmanagedApi(PFN_MYCALLBACK callback);
}

C#side

public delegate void MyCallback();
[DllImport("data_acquisition_sys.dll")]
public static extern void MyUnmanagedApi(MyCallback callback);

static void Main(string[] args) {

    MyUnmanagedApi(
    delegate()
    {
        Console.WriteLine("Called back by unmanaged side");
    }
    );
    }
}

我关注http://blogs.msdn.com/b/davidnotario/archive/2006/01/13/512436.aspx

错误

  

未处理的异常:System.EntryPointNotFoundException:无法在DLL“data_acquisition_sys.dll”中找到名为“MyUnmanagedApi”的入口点。 at the affect_detection_sys.Program.MyUnmanagedApi(MyCallback callback)at C:\ Users \ Public \ Docume

中的affect_detection_sys.Program.Main(String [] args)

2 个答案:

答案 0 :(得分:2)

对于所有感兴趣的各方,这是解决问题的有效方法。

C ++方

extern "C"
{
typedef void (*callback_function)();
callback_function gCBF;

__declspec(dllexport) void StartAcquisition(callback_function callback) {

    gCBF = callback;

    cout << "Acquisition started" << endl;
}

void DoWork() {
    gCBF()
}
}

C#side

[DllImport("data_acquisition_sys.dll", EntryPoint = "StartAcquisition")]
    public static extern void StartAcquisition(MyCallback callback);
StartAcquisition(delegate()
{

    Console.WriteLine("Called back by unmanaged side ");
}
);

请注意,callback_function是一个空方法(),因为返回并接受任何数据会导致运行时崩溃。这已在其他主题中报道,但答案尚未给出。

答案 1 :(得分:1)

MyUnmanagedApi返回int,您已声明void。试试这个:

public delegate void MyCallback();
[DllImport("data_acquisition_sys.dll")]
public static extern int MyUnmanagedApi(MyCallback callback);

static void Main(string[] args) {

    MyUnmanagedApi(
    delegate()
    {
        Console.WriteLine("Called back by unmanaged side");
    }
    );
    }
}