我正在尝试在C#中访问第三方.dll(非托管)。 我的方法如下所示
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;
}