-1

我正在尝试使用 dotnet 核心与树莓派 3 上的 NFC 读取器/写入器通信。

我不得不说我使用的不同的 libnfc 命令行工具都工作正常(也可以读取和轮询我的标签,这方面没有问题)。

这个想法是使用 dotnet core 和 C# 来编排 libnfc 库,它似乎工作正常,除非我调用的函数返回一个字符串,我收到以下错误消息:

*** Error in `./NfcTest': free(): invalid pointer: 0x6d4ebc00 ***

NfcTest 当然是我的应用程序的名称。

这是pinvoke定义

[DllImport("libnfc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string nfc_version();

请注意,在网上查找后,我确实[return]自己添加了属性,但它并没有改变任何结果。引发相同的错误。

libnfc中nfc_version的代码在这里:https ://github.com/nfc-tools/libnfc/blob/c3f739dea339a71c59d7d53ab6b0ecc477c3ab73/libnfc/nfc.c#L1325

它似乎返回一个“常数”,并且没有任何形式的释放。所以我的猜测是我错误地配置了其中一个属性。

另一个例子是我调用以下代码:

[DllImport("libnfc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern string nfc_device_get_name(IntPtr pnd);

虽然我可以使用指针(pnd 参数)完美地调用其他方法(即 poll),但调用此方法会返回与 Version 方法相同的错误。返回字符串的两种方法都让我想知道问题是否不在 DllImport 中,但我不太确定如何解决这个问题。

链接到该示例的 lib 代码:https ://github.com/nfc-tools/libnfc/blob/c3f739dea339a71c59d7d53ab6b0ecc477c3ab73/libnfc/nfc.c#L1215

任何智慧将不胜感激。

4

1 回答 1

1

Matthew Watson 的评论和他分享的链接有正确答案!

所以我像这样修改了 pinvoke 行:

[DllImport("libnfc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr nfc_version();

然后我这样称呼它:

public string Version()
{
    IntPtr ptr = Functions.nfc_version();
    var str = Marshal.PtrToStringAuto(ptr);
    return str;   
}

它就像一个魅力!

谢谢!

于 2021-02-23T09:39:00.400 回答