I am trying to Access a third Party .dll(unmanaged) in C#. My Methods are as shown below
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;
}
}
}
I am getting an error when I access the function 'SendCAN' the error is "Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." I looked at some suggestions but its not applicable for my code. Is there something wrong here. Please suggest. I cant find answer for my case. (64 bit Windows 7 OS)
The assosiated Struct as provided by 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;
}