Click here to Skip to main content
16,011,805 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a c dll that i am trying to call from c# using Dllimport.
I continue to get "Attempted to read or write to protected memory" when the function is called. I have tried just about anything i can think of, so any help would be appreciated.

Here is the C code
struct DocProcHandle {
	unsigned long Size;//sizeof(DocProcHandle)
	void* UserHandle;
	const char* DeviceName;
	unsigned long DeviceTypeId;
	unsigned long DeviceState;
	unsigned long OpenFlags;
	void* Reserved1;
};
typedef struct DocProcHandle *DPHandle;

BPS_DP_API DPHandle CDECLCALL_CONV DPOpenHandleEx(unsigned long deviceTypeId, const char* trkBaseWrite, const char* trkBaseConfig, const unsigned long openFlags);


Here is my c# code
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct DocProcHandle
{
  ulong Size;//sizeof(DocProcHandle)
  IntPtr UserHandle;
  [MarshalAs(UnmanagedType.LPStr)] string DeviceName;
  ulong DeviceTypeId;
  ulong DeviceState;
  ulong OpenFlags;
  IntPtr Reserved1;
};

[DllImport("DocProc.dll", EntryPoint = "DPOpenHandleEx", ExactSpelling = false, CallingConvention =CallingConvention.Cdecl)]
private static extern IntPtr DPOpenHandleEx(ulong deviceTypeId, [MarshalAs(UnmanagedType.LPStr)] string trkBaseWrite, [MarshalAs(UnmanagedType.LPStr)] string trkBaseConfig, [In] ulong openFlags);

static public void OpenHandle()
{
  string s = "C:\\temp";
  IntPtr a = DPOpenHandleEx((ulong)7, s, s, 0);
  //DocProcHandle h = (DocProcHandle)Marshal.PtrToStructure(a, typeof(DocProcHandle));
}


It blows up calling the DPOpenHandleEx method.
Any ideas are appreciated.

What I have tried:

I added the additional items to the dllimport line to further refine it.
Changing the return type marshal it.
Posted
Comments
Richard MacCutchan 25-Apr-18 11:48am    
Are you sure that the parameters you are passing to the function are correct?
lewisv 8-May-18 12:34pm    
You can see the header file. I think my dllimport looks like it would work for the given function.
As far as what my test program is passing in, they are the same as a sample c application that uses the same dll and method.
Ján Štrbík 31-Oct-18 6:06am    
I have exactly the same issue.. Did you resolve it anyhow?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900