Arturo Rosete Arturo Rosete - 3 years ago 338
C# Question

.DLL C++ function to C#

I'm using mpusbapi.dll in WPF project using C#.
In C++ the function prototype is:

DWORD MPUSBWrite(HANDLE handle,
PVOID pData,
DWORD dwLen,
PDWORD pLength,
DWORD dwMilliseconds);


And my p/invoke in C# is:

[DllImport("mpusbapi.dll")]
private static extern DWORD _MPUSBWrite(void* handle, void* pData, DWORD dwLen, DWORD* pLength, DWORD dwMilliseconds);


So, because I dont make all my project unsafe, I want to buid this next method to send data:

unsafe private void SendPacket(byte* SendData, UInt32 SendLength)
{
uint SendDelay = 10;
UInt32 SentDataLength;

openPipes();
MPUSBWrite(myOutPipe, &SendData, SendLength, &SentDataLength, SendDelay);
closePipes();
}


But Visual Studios show me an error with the variable type of the parameters. "Cannot convert from 'byte**' to 'system.IntPtr'" and "Cannot convert from 'uint*' to 'system.IntPtr'".
I am new using C # and now the pointers have me stuck. How should I translate the c++ parameter to C#? Thanks!

EDIT:
I didn't notice that I've changed the Pinvoke to:

[DllImport("mpusbapi.dll", CallingConvention = CallingConvention.Cdecl)]
static extern UInt32 _MPUSBWrite(IntPtr handle,IntPtr pData, UInt32 dwLen,IntPtr pLength, UInt32 dwMilliseconds);


ADD:
Removing the & in the method call did not fix the last errors and added this one "Use of unassigned local variable 'SendDataLenght'".

Answer Source

I don't see the need for any of this to be unsafe and use pointers. Making some basic assumptions on the parameter semantics, you might use this declaration:

[DllImport("mpusbapi.dll")]
private static extern uint _MPUSBWrite(
    IntPtr handle, 
    byte[] data, 
    uint dataLength, 
    out uint sentDataLength, 
    uint timeoutMS
);

I don't know what the calling convention should be. You use both stdcall and cdecl in the question. Rather than guessing, you need to find out definitively.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download