gpt4 book ai didi

c# - 尝试导入非托管 dll 时 Pinvoke "System.AccessViolationException"

转载 作者:行者123 更新时间:2023-11-30 15:38:28 25 4
gpt4 key购买 nike

我正在尝试为我公司使用的设备导入驱动程序 dll,但我似乎无法让它工作。我是 C# 新手,所以请放轻松。这与我昨天发表的一篇文章有​​关,我正在尝试将 C 程序转换为 C#。

我编写这段代码是为了开始理解 PInvoke

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace PInvokeTest {
class Program {
static void Main(string[] args) {
Int32 session_handle = 0;
Byte state_buffer = 0;
Int16 result = 1, PortNum = 1, PortType = 1;

session_handle = TMExtendedStartSession(PortNum, PortType);

result = TMSearch(session_handle, state_buffer, 1, 1, 0xEC);

if (result == 1)
Console.WriteLine("Device Found");

if (result == -201)
Console.WriteLine("Hardware Driver Not Found");

else
Console.WriteLine("Network Error");



Console.ReadKey();
}
[DllImport("IBFS32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern Int32 TMExtendedStartSession(Int16 PortNum, Int16 PortType);

[DllImport("IBFS32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern Int16 TMSearch(Int32 session_handle, Byte state_buffer, int p1, int p2, int p3);

}
}

我正在尝试使用这两个函数

TMExtendedStartSession http://files.maximintegrated.com/sia_bu/licensed/docs/1-wire_sdk_win/TMEX/exst8l9q.html

和TMSearch http://files.maximintegrated.com/sia_bu/licensed/docs/1-wire_sdk_win/TMEX/sear1ezy.html

当我运行 TMExthishedStartSession 时,我收到 System.AccessViolationException,但是当我单独运行 TMSearch 时,我收到一条消息“托管调试助手“PInvokeStackImbalance”已检测到“C:\PInvokeTest\Debug\PInvokeTest.vshost.exe”中存在问题。”

不过,函数 TMSearch 返回的值是 -201。

感谢任何帮助。

最佳答案

在 32 位 Windows 中,pascal 调用约定映射到 stdcall。在 WinDef.h(或在更现代的 SDK 中为 minwindef.h)顶部附近有一个 #define,它映射 pascal__stdcall

最重要的是,你的参数都是错误的。应该是这样的:

[DllImport("IBFS32.dll")]
public static extern int TMExtendedStartSession(
short PortNum,
short PortType,
IntPtr EnhancedOptions
);

[DllImport("IBFS32.dll")]
public static extern short TMSearch(
int session_handle,
IntPtr state_buffer,
short p1,
short p2,
short p3
);

state_buffer 参数也许最好声明为 byte[]。从这里很难判断语义是什么。

关于c# - 尝试导入非托管 dll 时 Pinvoke "System.AccessViolationException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21738576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com