C# 尝试读取或写入受保护的内存,内存或生成的版本没有问题
我正在尝试访问C#中的第三方.dll(非托管)。 我的方法如下所示C# 尝试读取或写入受保护的内存,内存或生成的版本没有问题,c#,dll,C#,Dll,我正在尝试访问C#中的第三方.dll(非托管)。 我的方法如下所示 static class NativeMethods { [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr h
static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
class VTCCAN
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int CAN_Transmission(ref can_msg message);
static readonly string dllfile = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\VTC1010_CAN_Bus.dll";
public int SendCAN(ref can_msg msg)
{
IntPtr pDll = NativeMethods.LoadLibrary(dllfile);
if (pDll == IntPtr.Zero)
{
MessageBox.Show("Loading Failed");
}
IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "CAN_Transmission");
CAN_Transmission sendCAN = (CAN_Transmission)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(CAN_Transmission));
int result = sendCAN(ref msg);
bool iresult = NativeMethods.FreeLibrary(pDll);
return result;
}
}
}
访问函数“SendCAN”时出错
错误是
“其他信息:试图读取或写入受保护的内存。这通常表示其他内存已损坏。”我查看了一些建议,但这不适用于我的代码。这里有什么问题吗。请建议。我找不到我的案子的答案。(64位Windows 7操作系统)
Abe提供的关联结构
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
public struct can_msg
{
/// unsigned short
public short ide;
/// unsigned int
public int id;
/// unsigned short
public short dlc;
/// unsigned char[100]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = NativeConstants.CAN_MSG_DATA_LEN)]
public string data;
/// unsigned short
public short rtr;
}
你也应该发布相关的
结构。对我来说,GetProcAddress有这样的注释:[DllImport(“kernel32”,CharSet=CharSet.Ansi,ExactSpelling=true,SetLastError=true)]
。LoadLibrary有以下内容:[DllImport(“kernel32”,SetLastError=true)]
。您还可以编写can\u传输sendCAN=(can\u传输)Marshal.GetDelegateForFunctionPointer(paddressofffunctiontocall))代码>。我还会在委托人之前添加不安全的关键字。您是否尝试过dll的dumpbin?传输是否能在.NET中可见?顺便说一句,如果您使用我昨天发布的结构,并对数据使用ByValTStr
,请确保为结构和字段()正确定义了字符集和SizeConst
。如果所有其他操作都失败,您可能希望尝试对字段执行LPStr
,并最终对结构执行Pack=1
。编译dll时使用的是什么?