【发布时间】:2016-11-25 14:26:16
【问题描述】:
我需要将 SglW32.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;
}
}
}
我正在使用加载函数从任何路径获取 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://stackoverflow.com/a/8836228/2451446
编辑:感谢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],就像对 Win32 API 函数所做的那样?只需确保将 DLL 分发在与 exe 相同的文件夹中(无论如何您都应该这样做)。桌面是放置 DLL 的错误位置,即使是用于开发 -
由于某种原因找不到 dll。我不知道为什么。
-
您在使用 Visual Studio 吗?你不能在你的项目中添加对 dll 的引用吗?右键单击项目“参考”文件夹并选择“添加参考”,然后使用浏览找到您的 .dll,选择它并单击确定。
-
是的,我正在使用 Visual Studio。不,我不能添加对项目的引用。如果我感冒了就很容易了。
-
请参阅this answer,了解如何始终让 DLL 具有编译器输出。