我正在触发我的托管代码并启动对非托管代码的调用。在非托管代码中存在回调函数。从非托管代码中,我可以在我的托管方法“DelegateMethod”中接收回调。但是,我无法获得来自非托管代码的正确参数/参数值。请帮助我解决这个问题。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace TestApp
{
public class Program
{
public delegate void fPointer(byte[] Sendapdu, ref int Sendlen, byte[] Recvapdu, ref int Recvlen);
public struct sCommsAbstraction
{
///Function to send and receive.
public fPointer pf_TxRx;
///Other functions if necessary, e.g. reset
}
// Create a method for a delegate.
public static void DelegateMethod(byte[] Sendapdu, ref int Sendlen, byte[] Recvapdu, ref int Recvlen)
{
//This is called from unmanaged code. I am not getting proper arguments
Console.WriteLine(Sendlen);
}
[DllImport("AuthLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int CmdLib_RegisterItsIO(ref sCommsAbstraction psCommsFunctions);
[DllImport("AuthLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int CmdLib_OpenApplication();
[DllImport("TransparentChannel.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int TC_Transceive(byte[] writeBuf, ref int writeBufLen, byte[] readBuf, ref int pwReadBufferLen);
static void Main(string[] args)
{
sCommsAbstraction psCommsFunctions = new sCommsAbstraction();
// Instantiate the delegate.
psCommsFunctions.pf_TxRx = DelegateMethod;
CmdLib_RegisterItsIO(ref psCommsFunctions);
CmdLib_OpenApplication();
}
}
}
这里有我未经管理的代码 - CmdLib.c
(该段内容涉及IT技术,翻译时保留了HTML标签)
//C code - unmanaged
typedef int32_t (*pFTransceive)(const uint8_t *prgbWriteBuffer, const uint16_t *pwWriteBufferLen, uint8_t *prgbReadBuffer, uint16_t *pwReadBufferLen);
typedef struct sCommsAbstraction
{
///Function to send and receive.
pFTransceive pf_TxRx;
///Other functions if necessary, e.g. reset
}sCommsAbstraction_d
static sCommsAbstraction_d sCommsAbstraction = {0};
void CmdLib_RegisterItsIO(const sCommsAbstraction_d *psCommsFunctions)
{
sCommsAbstraction.pf_TxRx = psCommsFunctions->pf_TxRx;
}
void CmdLib_OpenApplication()
{
sCommsAbstraction.pf_TxRx(rgbAPDUBuffer,&wTotalLength,rgbAPDUBuffer,&psApduData->wResponseLength);
}
pFTransceive
是如何定义的?pf_TxRx
是需要填充数组还是需要创建一个新数组? - Matteo Umilipublic delegate void fPointer([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] byte[] Sendapdu, ref int Sendlen, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=3)] byte[] Recvapdu, ref int Recvlen);
但我不确定它是否有效...而且它会很慢(因为缓冲区需要在 .NET 中被复制)。 - xanatos