111,125
社区成员
发帖
与我相关
我的任务
分享
byte[] buf = new byte[] { 2, 125 };
SI_Write(m_hUSBDevice, buf, written, ref written); //<---
uint written;
IntPtr ptrBuf = Marshal.AllocCoTaskMem(255);
SI_Write(m_hUSBDevice, ptrBuf , 255, ref written);
//read ptrBuf
Marshal.FreeCoTaskMem(ptrBuf);//free buf.
[DllImport("yourdll.dll", CallingConvention = CallingConvention.Cdecl)] //<----
static extern int SI_Write(IntPtr handle, byte[] buffer, int cbToWrite, ref int cbWritten);
{
byte[] buf = new byte[] { 1, 2, 3, 4 };
int written = 0;
SI_Write( yourHandle, buf, buf.Length, ref written);
}
#include "stdafx.h"
#include <windows.h>
extern "C" __declspec(dllexport) int __cdecl SI_Write(HANDLE Handle, LPVOID Buffer, DWORD NumBytesToWrite, DWORD *NumBytesWritten)
{
char buf[128] = {0};
for(int i=0; i<NumBytesToWrite && i<127; i++)
{
buf[i] = ((char*)Buffer)[i];
}
*NumBytesWritten = NumBytesToWrite;
MessageBoxA(NULL, buf, "", MB_OK);
return 1234;
}
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
byte[] buf = new byte[] { (byte)'1', (byte)'2', (byte)'3', (byte)'5' };
int written = 0;
SI_Write( IntPtr.Zero, buf, buf.Length, ref written); // message popped up
System.Diagnostics.Debug.Assert(written == buf.Length); // ok
}
[DllImport("MyDll.dll",CallingConvention=CallingConvention.Cdecl)]
static extern int SI_Write(IntPtr handle, byte[] buffer, int cbToWrite, ref int cbWritten);
}
}...
uint written = 0;
SI_Write( yourHandle, bufPtr, buf.Length, ref written);
Debug.Assert( written == (uint)buf.Length); // 检查是否所有数据全部写出
...
[DllImport("...")]
static extern void SI_Write(IntPtr Handle, IntPtr Buffer, uing NumBytesToWrite, ref uint NumBytesWritten);
{
byte[] buf = new byte[] { 1, 2, 3, 4 };
GCHandle gch = GCHandle.Alloc(buf, GCHandleType.Pinned); // need to pin the object, otherwise the CLR could move the object.
IntPtr bufPtr = gch.AddrOfPinnedObject();
uint written = 0;
SI_Write( yourHandle, bufPtr, buf.Length, ref written); // you don't need to Marshal.AllocHGlobal, use 'ref uint written' instead
gch.Free();
}