我需要将SglW32.dll导入我的解决方案中。
但是我收到了这个错误信息:
AccessViolation异常:试图读取或写入受保护的内存。这通常表明其他内存已损坏。
如果使用DllImport,我无法使用。在这种情况下,dll找不到。
以下是完整示例。
但是我收到了这个错误信息:
AccessViolation异常:试图读取或写入受保护的内存。这通常表明其他内存已损坏。
如果使用DllImport,我无法使用。在这种情况下,dll找不到。
以下是完整示例。
using System;
using System.Runtime.InteropServices;
namespace TestDllimport
{
class Program
{
static void Main(string[] args)
{
var a = new MyClass();
var result = a.getValue();
}
}
class FunctionLoader
{
[DllImport("Kernel32.dll")]
private static extern IntPtr LoadLibrary(string path);
[DllImport("Kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
public static Delegate LoadFunction<T>(string dllPath, string functionName)
{
var hModule = LoadLibrary(dllPath);
var functionAddress = GetProcAddress(hModule, functionName);
return Marshal.GetDelegateForFunctionPointer(functionAddress, typeof(T));
}
}
public class MyClass
{
//Define your path to dll.
//Get dll from: http://www.sg-lock.com/download/sglw32_v2_28.zip
private const string DLL_Path = @"C:\Users\admin123\Desktop\MyDlls\SglW32.dll";
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate ulong SglAuthentA(IntPtr AuthentCode);
static MyClass()
{
sglAuthentA = (SglAuthentA)FunctionLoader.LoadFunction<SglAuthentA>(DLL_Path, "SglAuthentA");
}
static private SglAuthentA sglAuthentA;
unsafe public ulong getValue()
{
IntPtr d = new IntPtr(5);
var a1 = sglAuthentA(d); // Exception IS HERE !!!!!
return a1;
}
}
}
我正在使用load函数从任何路径获取dll。之后,我从所需函数创建委托。在我的情况下,这个函数是SglAuthentA。
这个解决方案可以与另一个dll一起使用,但不能与SglW32.dll一起使用。
所需的dll:http://www.sg-lock.com/download/sglw32_v2_28.zip
手册:http://www.sg-lock.com/download/SG-Lock_Manual_Eng.pdf
来源1:https://dev59.com/q2ox5IYBdhLWcg3w_ZV0#8836228
编辑:感谢Hans Passant回答和ja72评论的解决方案
using System.Runtime.InteropServices;
namespace TestDllimport
{
class Program
{
static void Main(string[] args)
{
var testA = DllImportClass.SglAuthentA(new uint[] { 5, 6, 7 }, new uint[] { 5, 6, 7 }, new uint[] { 5, 6, 7 });
var testB = DllImportClass.SglAuthentB(new uint[] { 5, 6, 7 });
}
}
static class DllImportClass
{
[DllImport("SglW32.dll")]
public static extern uint SglAuthentA(uint[] AuthentCode0, uint[] AuthentCode1, uint[] AuthentCode2);
[DllImport("SglW32.dll")]
public static extern uint SglAuthentB(uint[] AuthentCode);
}
}
[DllImport]
?只需确保将 DLL 与您的 exe 文件放在同一文件夹中(无论如何,您应该这样做)。即使是开发过程中,将 DLL 放在桌面上也是错误的做法。 - Panagiotis Kanavos