Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.DLL C++;函数到C#_C#_C++_Pointers_Pinvoke - Fatal编程技术网

.DLL C++;函数到C#

.DLL C++;函数到C#,c#,c++,pointers,pinvoke,C#,C++,Pointers,Pinvoke,我正在使用C#在WPF项目中使用mpusbapi.dll。 在C++中,函数原型是: DWORD MPUSBWrite(HANDLE handle, PVOID pData, DWORD dwLen, PDWORD pLength, DWORD dwMilliseconds); 我在C#中的p/invoke是:

我正在使用C#在WPF项目中使用mpusbapi.dll。 在C++中,函数原型是:

DWORD MPUSBWrite(HANDLE handle,         
             PVOID pData,           
             DWORD dwLen,           
             PDWORD pLength,        
             DWORD dwMilliseconds);  
我在C#中的p/invoke是:

因此,因为我不会让我的项目变得不安全,所以我想构建下一个方法来发送数据:

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

     openPipes();
     MPUSBWrite(myOutPipe, &SendData, SendLength, &SentDataLength, SendDelay);
     closePipes();
}
但VisualStudio向我显示了一个参数变量类型的错误。“无法从'byte**'转换为'system.IntPtr'”和“无法从'uint*'转换为'system.IntPtr'”。 我刚开始使用C#,现在指针让我卡住了。如何将C++参数转换成C?谢谢

编辑: 我没有注意到我已将Pinvoke更改为:

[DllImport("mpusbapi.dll", CallingConvention = CallingConvention.Cdecl)]
static extern UInt32 _MPUSBWrite(IntPtr handle,IntPtr pData, UInt32 dwLen,IntPtr pLength, UInt32 dwMilliseconds);
添加:
在方法调用中删除&并没有修复上一个错误,而是添加了这一个“使用未分配的局部变量'SendDataLength'。

我认为这一切都不安全,不需要使用指针。在对参数语义进行一些基本假设后,可以使用以下声明:

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

我不知道呼叫约定应该是什么。您在问题中同时使用了
stdcall
cdecl
。不要猜测,你需要明确地找出答案。

只要试着删除方法调用中的
&
,比如
\MPUSBWrite(myOutPipe,SendData,SendLength,SentDataLength,SendDelay)…如果您有另一个错误,请将其添加到您的问题中。我进行了更改,似乎可以正常工作,但我有一个异常“PinvokeStackInbalance”。这通常是因为调用约定错误。读我的最后一段。您必须确定并指定调用约定。我不能在这里这么做。谢谢,伙计。我添加了调用约定cdecl,异常得到了解决。现在我正在测试这个程序,看看它是否有效
[DllImport("mpusbapi.dll")]
private static extern uint _MPUSBWrite(
    IntPtr handle, 
    byte[] data, 
    uint dataLength, 
    out uint sentDataLength, 
    uint timeoutMS
);