Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 非托管c++;代码 我有一个C++ DLL,需要在五月C项目中使用。_C#_C++_Dllimport_Unmanaged - Fatal编程技术网

C# 非托管c++;代码 我有一个C++ DLL,需要在五月C项目中使用。

C# 非托管c++;代码 我有一个C++ DLL,需要在五月C项目中使用。,c#,c++,dllimport,unmanaged,C#,C++,Dllimport,Unmanaged,以下是我的代码的重要部分: public static class MTSCRA_API { [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void DataReceiveDelegate([MarshalAsAttribute(UnmanagedType.LPStr)]String x); //More methods.... [DllImport("MTSCRA.

以下是我的代码的重要部分:

public static class MTSCRA_API
{
    [UnmanagedFunctionPointer(CallingConvention.StdCall)]
    public delegate void DataReceiveDelegate([MarshalAsAttribute(UnmanagedType.LPStr)]String x);

    //More methods....

    [DllImport("MTSCRA.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
    public static extern void OnDeviceConnectionStateChanged(IntPtr lpFuncNotify);

}
我使用它的地方:

public void Open()
        {
            if (!MTSCRA_API.IsDeviceConnected())
            {
                UInt32 result = MTSCRA_API.OpenDevice("");
                if (result == 0)
                {
                    MTSCRA_API.OnDataReceived(
                        Marshal.GetFunctionPointerForDelegate(
                        new Kiosk.Hardware.CardReaderMagTek.MTSCRA_API.DataReceiveDelegate(CardReaderMagTek_OnCardDataReceived)));
                }
            }
    }

    Mutex mutex = new Mutex();
    void CardReaderMagTek_OnCardDataReceived(String info)
    {
        try
        {
             //Do stuff
        }
        catch(Exception ex)
        {

        }
        finally
        {
            mutex.ReleaseMutex();
        }
        MTSCRA_API.ClearCardData();
        info = null;

    }
每次我在设备中刷卡时,都会调用
CardReaderMagTek\u OnCardDataReceived()
事件

执行
Open()
方法,调用事件
CardReaderMagTek\u OnCardDataReceived()
,但只调用了9次。A 10º代码崩溃,出现NullReferenceException而未输入事件,并且我无法访问调用堆栈

有人知道问题出在哪里吗

MTSCRA_API.OnDataReceived(
    Marshal.GetFunctionPointerForDelegate(
    new Kiosk.Hardware.CardReaderMagTek.MTSCRA_API.DataReceiveDelegate(
        CardReaderMagTek_OnCardDataReceived)
    )
);
你不能让你的代表活着。创建
DataReceiveDelegate
的实例,并将其传递给
GetFunctionPointerForDelegate
。但是在
GetFunctionPointerForDelegate
返回后,委托没有理由保持活动状态。在某个时候它会被收集


只要非托管函数需要调用委托,就可以将委托保存在托管变量中。

就是这样!我在这上面花了太多时间。。。谢谢