一个函数指针:
#define CALLBACK __stdcall
typedef VOID (CALLBACK* P_EVENT)( INT eNo, PVOID pData, PVOID pContxt );
一个结构体:
typedef struct tagSTR_DEF{
P_EVENT pRoutine; // CallBack Function
PVOID pMeasContext; // CallBack Function Use Variable
PVOID pTransBuffer; // Exchanges Buffer
} STR_DEF, *PSTR_DEF;
一个函数:
trans_StartA( int Device, PSTR_DEF pStr );
在C++工程中使用如下代码完成调用:
WORD m_Buffer[512];
STR_DEF acqInfo;
acqInfo.pRoutine = CallbackAcquire; // Callback function
acqInfo.pMeasContext = this;
acqInfo.pTransBuffer = m_Buffer;
CallbackAcquire( INT eNo, PVOID pData, PVOID pContxt )
{
…
//将m_Buffer中的数据输出
}
trans_StartA(Device, &acqInfo);
工作的目的是用C#调用这个函数
现在的C#代码是:
public delegate void P_EVENT(UInt32 eNo, ref ushort[] pData, ref UInt32 pContxt);
[StructLayout(LayoutKind.Sequential)]
public struct STR_DEF
{
[MarshalAs(UnmanagedType.FunctionPtr)]
public P_EVENT pRoutine;
[MarshalAs(UnmanagedType.U4)]
public Int32 pMeasContext;
unsafe public fixed ushort pTransBuffer[512];
[DllImport("trans.dll")]
public static extern UInt32 trans_StartA(UInt32 Device, ref STR_DEF pStr);
short[] Matrix = new short[512];
int Device = 0;
private void button2_Click(object sender, EventArgs e)
{
STR_DEF acqInfo;
acqInfo.pRoutine = new P_EVENT(CallbackAcquire);
acqInfo.pMeasContext = this.Handle;
acqInfo.pTransBuffer = Matrix;
trans_StartA(0, ref acqInfo);
}
public void CallbackAcquire(UInt32 eNo, IntPtr pData, IntPtr pContxt)
{
UInt32 a = eNo;
Marshal.Copy(pData, Matrix, 0, 512);
}
现在的结果是函数返回值都是正确的,但是Matrix数组中的数据全为零,有人说是应该根据地址读内存,有些人说是地址错误。应该怎么实现trans_StartA()的功能呢?请大家赐教,谢谢~