我想在c#中創建一個類來訪問C++ lib中的函數。函數在C++ dll中:
bool WriteReply(const unsigned char *reply, const unsigned long reply_length)
。C#包裝類爲c + +的DLL dll
其在C++中如何使用的示例: -
unsigned short msg_id = 0x0000;
byte msg_body[] = {(byte)(GetTickCount()/0x100)}; // a random value for loopback data
// combine the message id and message body into an big msg
unsigned long msg_length = sizeof(msg_id)+sizeof(msg_body);
byte* big_msg = new byte[msg_length];
big_msg[0] = LOBYTE(msg_id);
big_msg[1] = HIBYTE(msg_id);
memcpy((void*)&big_msg[2], (void*)msg_body, sizeof(msg_body));
// send the big message
if (!big_dev.WriteReply(big_msg, msg_length))
{
//do something here
}
我似乎無法從C#的功能傳遞給DLL(AccessViolationException
)。這是我試過的命令: -
byte[] bytearray = new byte[3] { 0x01, 0x02, 0x03 };
IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytearray.Length);
Marshal.Copy(bytearray, 0, unmanagedPointer, bytearray.Length);
bool writestatus = (bool)NativeMethods.WriteReply(unmanagedPointer, (uint)bytearray.Length);
,並在進口方面: -
[DllImport("dllname.dll", EntryPoint = "WriteReply")]
[return: MarshalAs(UnmanagedType.U1)]
internal static extern bool WriteReply(IntPtr msg, uint reply_length);
請讓我知道我在哪裏出了錯謝謝!
你就近了。減去reply_length參數,這是一個uint,而不是一個ulong。 – 2012-04-28 10:04:40
感謝Hans Passant的回覆,但它不起作用。我仍然得到AccessViolationException。還有其他建議嗎?你爲什麼說reply_length是uint,反正不是ulong?謝謝! – csharper 2012-04-29 08:14:49
因爲* long *在C++中是32位的。使用調試器來找出錯誤。 – 2012-04-29 09:20:31