0

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

C++ 端#include

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

C#端

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”的入口点。在 C:\Users\Public\Docume 中的 effect_detection_sys.Program.MyUnmanagedApi(MyCallback 回调) 中的 effect_detection_sys.Program.Main(String[] args)

4

2 回答 2

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#端

[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 是一个空方法 (),因为返回和接受 ANY 数据会导致运行时崩溃。这已在其他线程中报告过,但尚未给出答案。

于 2013-05-09T11:15:53.630 回答
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");
    }
    );
    }
}
于 2013-05-08T10:38:08.343 回答