I am calling into native code from managed code and I am having a bit of trouble figuring out how to properly marshal my code. In C, I have the following:
struct cHandle {
unsigned long handleLo;
unsigned long handleHi;
}
struct cBuffer {
unsigned long bufferSize;
unsigned long bufferType;
__field_bcount(bufferSize) void *bufferPtr;
}
struct cBufferDesc {
unsigned long bufferVersion;
unsigned long bufferCount;
_field_ecount(bufferCount) cBuffer *buffers;
}
uint __stdcall CMethod(
__in_opt cHandle* handle1,
__in_opt cHandle* handle2,
__in_opt wchar_t* wstr,
__in unsigned long long1,
__in unsigned long resevered1, // Reserved, always 0
__in unsigned long long2,
__in_opt cBufferDesc* inputBufferPtr,
__in unsigned long reserved2, // Reserved, always 0
__inout_opt cHandle* outHandle,
__inout_opt cBufferDesc* outputBufferPtr,
__out unsigned long * outLong,
__out_opt TimeStampStruct* timeStamp);
The behaviour of CMethod is as follows. outputBufferPtr will always output a value. If inputBufferPtr is NULL, handle2 should also be null and CMethod should follow different logic to give an initial output buffer, and if not CMethod should calculate the output buffer based on the data in the input buffer. I am having trouble getting my initial call to work. Additionally, I don't care about the timestamp, so I will not detail that struct, or make a C# equivalent. I have tried the following marshalling in C#:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Handle {
private IntPtr HandleLo;
private IntPtr HandleHi;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Buffer {
public uint Size; // Possibly unknown
public uint Type; // Always set.
public IntPtr Buffer; // Possibly unknown
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BufferDesc {
public uint Count; // Always 1 for my purposes
public uint Version; // Always set
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public Buffer[] BufferArray; // Will always be a size 1 array.
}
// Used for calling when we have an existing input buffer
[DllImport("mylib.dll", ExactSpelling = "true", CharSet = CharSet.Unicode, SetLastError = true)]
uint CMethod(
[In] ref Handle handle1,
[In] ref Handle handle2,
[In] IntPtr wstr,
[In] uint long1, // C# uint == C ulong
[In] uint reserved1,
[In] uint long2,
[In] ref BufferDesc inputBufferPtr,
[In] uint reserved2,
[In, Out] ref Handle outHandle,
[In, Out] ref BufferDesc outputBufferPtr,
[Out] out IntPtr outLong,
[Out] out IntPtr timestamp);
// Used for calling when we do not have an existing input buffer
// Here IntPtr.Zero will be passed in for handle2 and inputBufferPtr
[DllImport("mylib.dll", ExactSpelling = "true", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint CMethod(
[In] ref Handle handle1,
[In] IntPtr handle2,
[In] IntPtr wstr,
[In] uint long1, // C# uint == C ulong
[In] uint reserved1,
[In] uint long2,
[In] IntPtr inputBufferPtr,
[In] uint reserved2,
[In, Out] ref Handle outHandle,
[In, Out] ref BufferDesc outputBufferPtr,
[Out] out IntPtr outLong,
[Out] out IntPtr timestamp);
public static void WrapperMethod(
ref Handle handle1,
ref Handle handle2,
string wstr,
byte[] inputBuffer,
ref Handle outHandle,
out byte[] outputBuffer)
{
BufferDesc inputBufferDesc;
BufferDesc outputBufferDesc;
outputBufferDesc.Count = 1;
outputBufferDesc.Version = 0; // Real data not shown
outputBufferDesc.BufferArray = new Buffer[0];
outputBufferDesc.BufferArray[0].Count = 0;
outputBufferDesc.BufferArray[0].Type = 2; // Real data not shown
outputBufferDesc.BufferArray[0].Buffer = IntPtr.Zero;
IntPtr wstrPtr = Marshal.StringToCoTaskMemUni(wstr);
IntPtr ignoredOutLong;
IntPtr ignoredTimestamp;
if (null != inputBuffer)
{
inputBufferDesc.Count = 1;
inputBufferDesc.Version = 0; // Real data not shown
inputBufferDesc.BufferArray = new Buffer[1];
inputBufferDesc.BufferArray[0].Size = inputBuffer.Length;
inputBufferDesc.BufferArray[0].Type = 2; // Real data not shown
inputBufferDesc.BufferArray[0].Buffer = GCHandle.Alloc(inputBuffer, GCHandleType.Pinned).AddrOfPinnedObject();
CMethod(
ref handle1,
ref handle2,
wstrPtr,
0, // Real data not shown
0,
0, // Real data not shown
ref inputBufferDesc,
0,
ref outHandle,
ref outputBufferDesc,
out ignoreOutLong,
out ignoreTimestamp);
}
else
{ ///////////////////////////////////////////////////////////////////////
// This is the call I am taking and also where the code is crashing. //
CMethod( //
ref handle1, //
IntPtr.Zero, //
wstrPtr, //
0, // Real data not shown //
0, //
0, // Real data not shown //
IntPtr.Zero, //
0, //
ref outHandle, //
ref outputBufferDesc, //
out ignoreOutLong, //
out ignoreTimestamp); //
///////////////////////////////////////////////////////////////////////
}
// Do Cleanup. Not reached at this point.
}
The error that I am getting is that I am trying to access read or write protected memory. If there is anything you can see which is obviously wrong with how I am marshalling or if I am pinning wrong, or just not pinning where I should be please, or if you can see any other issues let me know.
The issue was with my output buffer. I wasn't assigning an empty array of size one to outputBufferDesc.Buffers, and the native code tried to write to memory that wasn't allocated for that purpose. I also couldn't marshal it as a byvalue array. Instead my struct looks like this:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct BufferDesc
{
public uint Version;
public uint Count;
public IntPtr Buffers;
}
And I pin an empty SecurityBuffer array of size 1 and give the address to Buffers.
Related
I'm in the process of writing a basic .NET wrapper for the unmanaged Offline Registry Library. Currently, I'm working to implement a class, OfflineRegistryKey, which is modelled on Microsoft.Win32.RegistryKey but intended for use with offline Registry Hives rather than the live system Registry.
While trying to implement an equivalent to the GetValueNames() method, which enumerates values within a Registry key, I ran into some trouble trying to P/Invoke the unmanaged function OREnumValue from Offreg.dll. The only parameter I'm interested in in this case is the name of the value, or lpValueName.
My P/Invoke code for OREnumValue:
[DllImport("Offreg.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern uint OREnumValue(
SafeRegistryHandle Handle,
uint dwIndex,
IntPtr lpValueName,
ref uint lpcValueName,
IntPtr lpType,
IntPtr lpData,
ref uint lpcbData);
I call the function like this in my code:
public class OfflineRegistryKey : IDisposable
{
private readonly SafeRegistryHandle hKey;
public string[] GetValueNames()
{
uint dwIndex = 0;
while (true)
{
uint lpcValueName = 0;
uint lpcbData = 0;
uint returnValue = OREnumValue(hKey, dwIndex, IntPtr.Zero, ref lpcValueName, IntPtr.Zero, IntPtr.Zero, ref lpcbData);
if (returnValue == 0x0103) // ERROR_NO_MORE_ITEMS
{
break;
}
else if (returnValue == 0x00EA) // ERROR_MORE_DATA
{
// Do stuff...
}
else
{
throw new Win32Exception(returnValue);
}
dwIndex++;
}
}
}
Ideally, The call to OREnumKey would return 0xEA (ERROR_MORE_DATA), after which it would be called again until it reaches the end index and returns 0x103 (ERROR_NO_MORE_ITEMS).
The return value I'm getting (which throws an exception at runtime and halts execution on the first iteration of the loop) is 0x57 (ERROR_INVALID_PARAMETER), which leads me to believe that I've somehow screwed up the P/Invoke call. I would very much appreciate if someone with a greater knowledge of P/Invoke and the Windows API could provide me with some guidance.
Thanks!
Your P/Invoke declaration is not correct, because lpValueName does not accept NULL according to the documentation.
It's also defined as Unicode, so you should specify that.
[DllImport("Offreg.dll", CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint OREnumValue(
SafeRegistryHandle Handle,
uint dwIndex,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpValueName,
ref uint lpcValueName,
IntPtr lpType,
IntPtr lpData,
ref uint lpcbData);
Then you simply pass a pre-assigned buffer. Theoretically it could be 16383 characters, you could use ORQueryInfoKey to get the max size, or just allocate the whole thing. I suggest you allocate it only once, outside the loop.
public string[] GetValueNames()
{
const int ERROR_SUCCESS = 0;
const int ERROR_NO_MORE_ITEMS = 0x103;
const int ERROR_MORE_DATA = 0x00EA;
uint dwIndex = 0;
string lpValueName = new StringBuilder(16384);
while (true)
{
uint lpcValueName = 0;
uint lpcbData = 0;
uint returnValue = OREnumValue(hKey, dwIndex, IntPtr.Zero, ref lpcValueName, IntPtr.Zero, IntPtr.Zero, ref lpcbData);
if (returnValue == ERROR_NO_MORE_ITEMS)
{
break;
}
else if (returnValue == ERROR_MORE_DATA)
{
// Do stuff...
}
else if (returnValue != ERROR_SUCCESS)
{
throw new Win32Exception(returnValue);
}
dwIndex++;
}
}
I've tried replacing
public static extern Int64 ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesRead);
with
public static extern bool ReadProcessMemory(int hProcess, Int64 lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);
and it still doesn't do anything except give me errors. My full code if it matters:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Transient.Utilities
{
/// <summary>
/// ProcessMemoryReader is a class that enables direct reading a process memory
/// </summary>
class ProcessMemoryReaderApi
{
// constants information can be found in <winnt.h>
[Flags]
public enum ProcessAccessType
{
PROCESS_TERMINATE = (0x0001),
PROCESS_CREATE_THREAD = (0x0002),
PROCESS_SET_SESSIONID = (0x0004),
PROCESS_VM_OPERATION = (0x0008),
PROCESS_VM_READ = (0x0010),
PROCESS_VM_WRITE = (0x0020),
PROCESS_DUP_HANDLE = (0x0040),
PROCESS_CREATE_PROCESS = (0x0080),
PROCESS_SET_QUOTA = (0x0100),
PROCESS_SET_INFORMATION = (0x0200),
PROCESS_QUERY_INFORMATION = (0x0400),
PROCESS_QUERY_LIMITED_INFORMATION = (0x1000)
}
// function declarations are found in the MSDN and in <winbase.h>
// HANDLE OpenProcess(
// DWORD dwDesiredAccess, // access flag
// BOOL bInheritHandle, // handle inheritance option
// DWORD dwProcessId // process identifier
// );
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId);
// BOOL CloseHandle(
// HANDLE hObject // handle to object
// );
[DllImport("kernel32.dll")]
public static extern Int32 CloseHandle(IntPtr hObject);
// BOOL ReadProcessMemory(
// HANDLE hProcess, // handle to the process
// LPCVOID lpBaseAddress, // base of memory area
// LPVOID lpBuffer, // data buffer
// SIZE_T nSize, // number of bytes to read
// SIZE_T * lpNumberOfBytesRead // number of bytes read
// );
[DllImport("kernel32.dll")]
public static extern Int64 ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesRead);
// BOOL WriteProcessMemory(
// HANDLE hProcess, // handle to process
// LPVOID lpBaseAddress, // base of memory area
// LPCVOID lpBuffer, // data buffer
// SIZE_T nSize, // count of bytes to write
// SIZE_T * lpNumberOfBytesWritten // count of bytes written
// );
[DllImport("kernel32.dll")]
public static extern Int64 WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesWritten);
class PMR
{
}
}
public class ProcessMemoryReader
{
public Process ReadProcess { get; set; }
private IntPtr handle;
public void OpenProcess()
{
ProcessMemoryReaderApi.ProcessAccessType access = ProcessMemoryReaderApi.ProcessAccessType.PROCESS_QUERY_INFORMATION |
ProcessMemoryReaderApi.ProcessAccessType.PROCESS_VM_READ |
ProcessMemoryReaderApi.ProcessAccessType.PROCESS_VM_WRITE |
ProcessMemoryReaderApi.ProcessAccessType.PROCESS_VM_OPERATION;
handle = ProcessMemoryReaderApi.OpenProcess((uint)access, 1, (uint)ReadProcess.Id);
}
public void CloseHandle()
{
int returnValue = ProcessMemoryReaderApi.CloseHandle(handle);
if (returnValue != 0)
throw new Exception("Closing Handle Failure");
}
public Byte[] ReadMemory(IntPtr memoryAdress, uint bytesToRead, out int bytesRead)
{
byte[] buffer = new byte[bytesToRead];
IntPtr pBytesRead = IntPtr.Zero;
ProcessMemoryReaderApi.ReadProcessMemory(handle, memoryAdress, buffer, bytesToRead, out pBytesRead);
bytesRead = pBytesRead.ToInt32();
return buffer;
}
public void WriteMemory(IntPtr memoryAddress, byte[] buffer, out int bytesWritten)
{
IntPtr pBytesWritten = IntPtr.Zero;
ProcessMemoryReaderApi.WriteProcessMemory(handle, memoryAddress, buffer, (uint)buffer.Length, out pBytesWritten);
bytesWritten = pBytesWritten.ToInt32();
}
}
}
Any help would be great. I used a tutorial for the code, please don't hurt me.
Errors: 1. Argument 5 must be passed with the ref keyword | 2. Argument 2: Cant convert from System.IntPtr to long | 3. Argument 1: Cant convert from System.IntPtr to int. These all take place on line 101, which is
ProcessMemoryReaderApi.ReadProcessMemory(handle, memoryAdress, buffer, bytesToRead, out pBytesRead);
IntPtr can hold 4 bytes pointers when building x86, and 8 byte when building in x64 mode. If you want your code to be universal for x86 and x64, just use IntPtr for all pointer types. You do not need to change them to int64.
The first RPM pinvoke definition uses "out" and your second one uses "ref". You did not update your actual function calls to use ref, causing your compiler errors.
Just use "out" and stick to IntPtr
Change dwSize to be a IntPtr
Then call the function using the correct data types
Compile for x64, and your problem will be solved.
If required you can use IntPtr.toInt64() etc...
I want to call 5 WinDivert functions in a C# code, first reflex : PInvoke here are the signatures :
internal enum WINDIVERT_LAYER
{
WINDIVERT_LAYER_NETWORK = 0, /* Network layer. */
WINDIVERT_LAYER_NETWORK_FORWARD = 1 /* Network layer (forwarded packets) */
}
internal const UInt64 WINDIVERT_FLAG_SNIFF = 1;
/*
* typedef struct
{
UINT32 IfIdx;
UINT32 SubIfIdx;
UINT8 Direction;
} WINDIVERT_ADDRESS, *PWINDIVERT_ADDRESS;
* */
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct WINDIVERT_ADDRESS
{
UInt32 IfIdx;
UInt32 SubIfIdx;
byte Direction;
}
/*
* typedef struct
{
UINT8 HdrLength:4;
UINT8 Version:4;
UINT8 TOS;
UINT16 Length;
UINT16 Id;
UINT16 FragOff0;
UINT8 TTL;
UINT8 Protocol;
UINT16 Checksum;
UINT32 SrcAddr;
UINT32 DstAddr;
} WINDIVERT_IPHDR, *PWINDIVERT_IPHDR;
* */
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct WINDIVERT_IPHDR
{
byte HdrLengthAndVersion;
byte TOS;
UInt16 Length;
UInt16 Id;
UInt16 FragOff0;
byte TTL;
byte Protocol;
UInt16 Checksum;
UInt32 SrcAddr;
UInt32 DstAddr;
}
/*
* typedef struct
{
UINT16 SrcPort;
UINT16 DstPort;
UINT16 Length;
UINT16 Checksum;
} WINDIVERT_UDPHDR, *PWINDIVERT_UDPHDR;
* */
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct WINDIVERT_UDPHDR
{
UInt16 SrcPort;
UInt16 DstPort;
UInt16 Length;
UInt16 Checksum;
}
/*
* HANDLE WinDivertOpen(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__in INT16 priority,
__in UINT64 flags
);
* */
[DllImport("WinDivert.dll", EntryPoint = "WinDivertOpen", SetLastError = true, CharSet = CharSet.Auto,
ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr WinDivertOpen(
[MarshalAs(UnmanagedType.LPStr)] string filter,
WINDIVERT_LAYER layer,
Int16 priority,
UInt64 flags);
/*
* BOOL WinDivertClose(
__in HANDLE handle
);
* */
[DllImport("WinDivert.dll", EntryPoint = "WinDivertClose", SetLastError = true, CharSet = CharSet.Auto,
ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
[return:MarshalAs(UnmanagedType.Bool)]
internal static extern bool WinDivertClose(IntPtr handle);
/*
* BOOL WinDivertRecv(
__in HANDLE handle,
__out PVOID pPacket,
__in UINT packetLen,
__out_opt PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *recvLen
);
* */
[DllImport("WinDivert.dll", EntryPoint = "WinDivertRecv", SetLastError = true, CharSet = CharSet.Auto,
ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WinDivertRecv(IntPtr handle, out IntPtr pPacket, uint packetLen, [Optional] out IntPtr pAddr, [Optional] out uint readLen);
/*
* BOOL WinDivertHelperParsePacket(
__in PVOID pPacket,
__in UINT packetLen,
__out_opt PWINDIVERT_IPHDR *ppIpHdr,
__out_opt PWINDIVERT_IPV6HDR *ppIpv6Hdr,
__out_opt PWINDIVERT_ICMPHDR *ppIcmpHdr,
__out_opt PWINDIVERT_ICMPV6HDR *ppIcmpv6Hdr,
__out_opt PWINDIVERT_TCPHDR *ppTcpHdr,
__out_opt PWINDIVERT_UDPHDR *ppUdpHdr,
__out_opt PVOID *ppData,
__out_opt UINT *pDataLen
);
* */
[DllImport("WinDivert.dll", EntryPoint = "WinDivertHelperParsePacket", SetLastError = true, CharSet = CharSet.Auto,
ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WinDivertHelperParsePacket(IntPtr pPacket, uint packetLen, [Optional] out IntPtr ppIpHdr, [Optional] out IntPtr ppIpv6Hdr,
[Optional] out IntPtr ppIcmpHdr, [Optional] out IntPtr ppTcpHdr, [Optional] out IntPtr ppUdpHdr, [Optional] out IntPtr ppData,
[Optional]out uint pDataLen);
/*
* BOOL WinDivertSend(
__in HANDLE handle,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *sendLen
);
* */
[DllImport("WinDivert.dll", EntryPoint = "WinDivertSend", SetLastError = true, CharSet = CharSet.Auto,
ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WinDivertSend(IntPtr handle, IntPtr pPacket, uint packetLen, IntPtr pAddr, [Optional] out uint sendLen);
I have managed to avoid (87 = ERROR_INVALID_PARAMETER), (998 = ERROR_NOACCESS) errors on calls to WinDivertOpen(), WinDivertClose() and WinDivertRecv() but I'm still getting System.AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory has been corrupted and (998 = ERROR_NOACCESS) when trying to call WinDivertHelperParsePacket().
Here's the code :
static void Main(string[] args)
{
const uint MAXBUF = 0xFFFF;
IntPtr handle;
IntPtr addr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeMethods.WINDIVERT_ADDRESS)));
IntPtr packet = Marshal.AllocHGlobal((int)MAXBUF);
uint packetLen;
IntPtr ip_header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeMethods.WINDIVERT_IPHDR)));
IntPtr udp_header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeMethods.WINDIVERT_UDPHDR)));
IntPtr payload;
uint payload_len;
uint sendLen;
IntPtr opt_param = IntPtr.Zero;
byte[] managedPacket;
IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
handle = NativeMethods.WinDivertOpen("udp.DstPort == 53", NativeMethods.WINDIVERT_LAYER.WINDIVERT_LAYER_NETWORK, 404, NativeMethods.WINDIVERT_FLAG_SNIFF);
if (handle == INVALID_HANDLE_VALUE) Console.WriteLine("open error:" + Marshal.GetLastWin32Error());
else
{
while (true)
{
if (!NativeMethods.WinDivertRecv(handle, out packet, MAXBUF, out addr, out packetLen))
{
Console.WriteLine("Recv error:" + Marshal.GetLastWin32Error());
continue;
}
try
{
managedPacket = new byte[(int)packetLen];
Marshal.Copy(packet, managedPacket, 0, (int)packetLen); // causes AccessViolationException
Console.WriteLine("---------------------------------");
/*for (int i = 0; i < packetLen; i++)
{
Console.Write("{0:X}", managedPacket[i]);
}*/
Console.WriteLine("---------------------------------");
}
catch(Exception ex)
{
Console.WriteLine("copy error :" + ex.Message);
}
if (!NativeMethods.WinDivertHelperParsePacket(packet, packetLen, out ip_header, out opt_param, out opt_param, out opt_param, out udp_header, out payload, out payload_len)) // causes AccessViolationException
{
Console.WriteLine("Parse error:" + Marshal.GetLastWin32Error());
//continue;
}
if (!NativeMethods.WinDivertSend(handle, packet, packetLen, addr, out sendLen))
{
Console.WriteLine("Send error:" + Marshal.GetLastWin32Error());
continue;
}
}
/*if (!NativeMethods.WinDivertClose(handle))
Console.WriteLine("close error:" + Marshal.GetLastWin32Error());*/
}
Console.ReadKey();
}
My boss told me that it's better/easier to write a COM object in C++ that wraps the C calls and expose it to C# to avoid the marshaling and memory handling pain. Should I stick to PInvoke or go the COM way ?
EDIT : Updates
I have tried two different ways of allocating unmanaged memory and both failed (unsafe code allowed) :
byte[] managedPacket = new byte[(int)packetLen];
NativeMethods.WINDIVERT_ADDRESS windivertAddr = new NativeMethods.WINDIVERT_ADDRESS();
GCHandle managedPacketHandle = GCHandle.Alloc(managedPacket, GCHandleType.Pinned);
IntPtr managedPacketPointer = managedPacketHandle.AddrOfPinnedObject();
GCHandle windivertAddrHandle = GCHandle.Alloc(windivertAddr, GCHandleType.Pinned);
IntPtr windivertAddrPointer = managedPacketHandle.AddrOfPinnedObject();
NativeMethods.WinDivertRecv(handle, out managedPacketPointer, (uint)(packetLen * Marshal.SizeOf(typeof(System.Byte))), out windivertAddrPointer , out readLen);
// output of managed array and struct fields = 0 and it still causes unhandled AccessViolationException even inside a try/catch
managedPacketHandle.Free();
windivertAddrPointer.Free();
and :
IntPtr packet = Marshal.AllocHGlobal((int)packetLen * Marshal.SizeOf(typeof(System.Byte)));
IntPtr addr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeMethods.WINDIVERT_ADDRESS)));
NativeMethods.WinDivertRecv(handle, out packet, (uint)(packetLen * Marshal.SizeOf(typeof(System.Byte))), out addr, out readLen)
byte[] managedPacket = new byte[(int)packetLen];
Marshal.Copy(packet, managedPacket, 0, (int)readLen);
NativeMethods.WINDIVERT_ADDRESS windivertAddr = (NativeMethods.WINDIVERT_ADDRESS)Marshal.PtrToStructure(addr, typeof(NativeMethods.WINDIVERT_ADDRESS));
// no output of managed array and struct fields and the same unhandled AccessViolationException
Marshal.FreeHGlobal(addr);
Marshal.FreeHGlobal(packet);
Also sometimes inside a loop, WinDivRecv fails with LastWin32Error : 6 = INVALID_HANDLE_VALUE is it because the GC is messing with the handle ? I tried GC.KeepAlive(handle) and it didn't change anything.
C++\CLI wrapper : (bridge between unmanaged C DLL and managed C# code)
[Suggested option in the comments below]
I followed these steps :
Create a C++/CLI library project
Create a Native C++ class that wraps the C functions
Create a managed C++/CLI class with a field pointing to a native class instance and wraps all the unmanaged methods and do the necessary marshalling.
Try to build ==> fails with the famous LNK2019 and LNK2028
Should I add the WinDivert DLL as a reference or only WinDivert.h ? What about the kernel driver .sys files ?
And honestly it's not easier than PInvoke but a lot worse, I still have to do the same marshalling of non-blittable data types and struct/enum definitions !
I am trying to conver a C SDK to C# and am running into a "Illegal Parameter" error on the conversion of a C function.
The details of the C SDK function are listed below
#ifndef LLONG
#ifdef WIN32
#define LLONG LONG
#else //WIN64
#define LLONG INT64
#endif
#endif
#ifndef CLIENT_API
#define CLIENT_API __declspec(dllexport)
#endif
#else
#ifndef CLIENT_API
#define CLIENT_API __declspec(dllimport)
#endif
#endif
#define CALLBACK __stdcall
#define CALL_METHOD __stdcall //__cdecl
// Configuration type,corresponding to CLIENT_GetDevConfig and CLIENT_SetDevConfig
#define DH_DEV_DEVICECFG 0x0001 // Device property setup
#define DH_DEV_NETCFG 0x0002 // Network setup
#define DH_DEV_CHANNELCFG 0x0003 // Video channel setup
#define DH_DEV_PREVIEWCFG 0x0004 // Preview parameter setup
#define DH_DEV_RECORDCFG 0x0005 // Record setup
#define DH_DEV_COMMCFG 0x0006 // COM property setup
#define DH_DEV_ALARMCFG 0x0007 // Alarm property setup
#define DH_DEV_TIMECFG 0x0008 // DVR time setup
#define DH_DEV_TALKCFG 0x0009 // Audio talk parameter setup
#define DH_DEV_AUTOMTCFG 0x000A // Auto matrix setup
#define DH_DEV_VEDIO_MARTIX 0x000B // Local matrix control strategy setup
#define DH_DEV_MULTI_DDNS 0x000C // Multiple ddns setup
#define DH_DEV_SNAP_CFG 0x000D // Snapshot corresponding setup
#define DH_DEV_WEB_URL_CFG 0x000E // HTTP path setup
#define DH_DEV_FTP_PROTO_CFG 0x000F // FTP upload setup
#define DH_DEV_INTERVIDEO_CFG 0x0010 // Plaform embedded setup. Now the channel parameter represents the platform type.
// Search configuration information
CLIENT_API BOOL CALL_METHOD CLIENT_GetDevConfig(LLONG lLoginID, DWORD dwCommand, LONG lChannel, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned,int waittime=500);
The C# info is as follows:
// [DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.StdCall)]
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
// [DllImport("dhnetsdk.dll")]
public static extern bool CLIENT_GetDevConfig(long lLoginID,
uint dwCommand,
long lChannel,
IntPtr lpBuffer,
uint dwOutBufferSize,
uint lpBytesReturned,
int waittime = 500);
And I am calling the method as follows:
int t = 500;
uint BytesReturned = 0;
uint c = 8;
var lpOutBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NET_TIME)));
if (CLIENT_GetDevConfig(lLogin, c, 0, lpOutBuffer, (uint)Marshal.SizeOf(typeof(NET_TIME)), BytesReturned, t) == false)
{
Console.WriteLine("GetDevConfig FAILED");
}
[StructLayout(LayoutKind.Sequential)]
public struct NET_TIME
{
// [FieldOffset(0)]
uint dwYear;
// [FieldOffset(4)]
uint dwMonth;
// [FieldOffset(4)]
uint dwDay;
// [FieldOffset(4)]
uint dwHour;
// [FieldOffset(4)]
uint dwMinute;
// [FieldOffset(4)]
uint dwSecond;
}
I am positive the lLogin is correct since I successfully logged into the device using it.
But when I check GetLastError immediately after the call to GetDevConfig fails, it indicates a illegal parameter. So, can anybody point out the illegal parameter in the above code?
The following is my C# code with the illegal parameter issues...
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
static public int lLogin;
public delegate void fDisConnect(long lLoginID, IntPtr pchDVRIP, long nDVRPort, uint dwUser);
public delegate void fHaveReConnect(long lLoginID, IntPtr pchDVRIP, long nDVRPort, uint dwUser);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool CLIENT_Init(fDisConnect cbDisConnect, uint dwUser);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void CLIENT_SetAutoReconnect(fHaveReConnect cbHaveReconnt, uint dwUser);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int CLIENT_Login(string pchDVRIP, ushort wDVRPort, string pchUserName, string pchPassword, NET_DEVICEINFO lpDeviceInfo, IntPtr error);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CLIENT_GetDevConfig(
int loginId,
uint command,
int channel,
out NET_TIME buffer,
out uint bufferSize,
IntPtr lpBytesReturned,
int waittime = 500);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool CLIENT_Logout(long lID);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void CLIENT_Cleanup();
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern uint CLIENT_GetLastError();
public static void fDisConnectMethod(long lLoginID, IntPtr pchDVRIP, long nDVRPort, uint dwUser)
{
System.Console.WriteLine("Disconnect");
return;
}
public static void fHaveReConnectMethod(long lLoginID, IntPtr pchDVRIP, long nDVRPort, uint dwUser)
{
System.Console.WriteLine("Reconnect success");
return;
}
[StructLayout(LayoutKind.Sequential)]
public class NET_DEVICEINFO
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 48)]
public byte[] sSerialNumber;
public byte byAlarmInPortNum;
public byte byAlarmOutPortNum;
public byte byDiskNum;
public byte byDVRType;
public byte byChanNum;
}
[StructLayout(LayoutKind.Sequential)]
public struct NET_TIME
{
uint dwYear;
uint dwMonth;
uint dwDay;
uint dwHour;
uint dwMinute;
uint dwSecond;
}
public static void Main()
{
fDisConnect fDisConnecthandler = fDisConnectMethod;
fHaveReConnect fHaveReConnecthandler = fHaveReConnectMethod;
NET_DEVICEINFO deviceinfo = new NET_DEVICEINFO();
IntPtr iRet = new IntPtr(0);
CLIENT_Init(fDisConnectMethod, 0);
CLIENT_SetAutoReconnect(fHaveReConnecthandler, 0);
lLogin = CLIENT_Login("192.168.1.198", 31111, "user", "password", deviceinfo, iRet);
if (lLogin <= 0)
Console.WriteLine("Login device failed");
else
{
Console.WriteLine("Login device successful");
byte[] byteout = new byte[20];
const int t = 500;
IntPtr BytesReturned;
BytesReturned = IntPtr.Zero;
const uint c = 8;
NET_TIME nt;
uint sizeofnt = (uint)Marshal.SizeOf(typeof(NET_TIME));
if (CLIENT_GetDevConfig(lLogin, c, 0, out nt, out sizeofnt, BytesReturned, t) == false)
{
uint gle = CLIENT_GetLastError();
Console.WriteLine("getDevConfig failed");
}
CLIENT_Logout(lLogin);
CLIENT_Cleanup();
}
}
}
And here is my C code that I'm trying to port to C#. It works without any issues..
#pragma comment(lib,"dhnetsdk.lib")
#include <Windows.h>
#include <stdio.h>
#include <conio.h>
#include "dhnetsdk.h"
void CALLBACK DisConnectFunc(LONG lLoginID, char *pchDVRIP, LONG nDVRPort, DWORD dwUser)
{
printf("Disconnect.");
return;
}
void CALLBACK AutoConnectFunc(LONG lLoginID,char *pchDVRIP,LONG nDVRPort,DWORD dwUser)
{
printf("Reconnect success.");
return;
}
int main(void)
{
NET_TIME nt = {0};
NET_DEVICEINFO deviceInfo = {0};
unsigned long lLogin = 0;
LPVOID OutBuffer;
int iRet = 0;
DWORD dwRet = 0;
//Initialize the SDK, set the disconnection callback functions
CLIENT_Init(DisConnectFunc,0);
//Setting disconnection reconnection success of callback functions. If don't call this interface, the SDK will not break reconnection.
CLIENT_SetAutoReconnect(AutoConnectFunc,0);
lLogin = CLIENT_Login("192.168.1.108",31111,"user","password",&deviceInfo, &iRet);
if(lLogin <= 0)
{
printf("Login device failed");
}
else
{
OutBuffer = (LPVOID)malloc(sizeof(NET_TIME));
memset(OutBuffer, 0, sizeof(NET_TIME));
if(CLIENT_GetDevConfig( lLogin, 8 /* DH_DEV_TIMECFG */, 0, OutBuffer, sizeof(NET_TIME), &dwRet, 500) == FALSE)
{
printf("Failed\n");
}
else
{
memcpy(&nt, OutBuffer, sizeof(nt));
printf("Time %d %d %d %d %d %d\n", nt.dwYear,nt.dwMonth,nt.dwDay, nt.dwHour,nt.dwMinute, nt.dwSecond);
}
_getch();
}
CLIENT_Logout(lLogin);
CLIENT_Cleanup();
return 0;
}
Your extern function is wrongly defined. Let's take your C call example.
// Search configuration information
CLIENT_API BOOL CALL_METHOD CLIENT_GetDevConfig(LLONG lLoginID, DWORD dwCommand, LONG lChannel, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned,int waittime=500);
As stated in comment of your post, the length of LONG is 32-bit in Win32, so you have to use an int. You can also use the keyword out to get your structure without manually use the Mashaller. I would define your function as that.
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CLIENT_GetDevConfig(int loginId, uint command, int channel, out NET_TIME buffer, out uint bufferSize, IntPtr lpBytesReturned, int waittime = 500);
Note the presence of the additional attribute MarshalAs. It indicates how the managed code should consider the return value of the pinvoke'd function.
Here are the differences that I can see:
The C++ code:
CLIENT_API BOOL CALL_METHOD CLIENT_GetDevConfig(
LLONG lLoginID,
DWORD dwCommand,
LONG lChannel,
LPVOID lpOutBuffer,
DWORD dwOutBufferSize,
LPDWORD lpBytesReturned,
int waittime
);
Now, LLONG is pointer sized, 32 bit under x86, 64 bit under x64. That translates to IntPtr for C#. I'd declare the p/invoke like this:
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CLIENT_GetDevConfig(
IntPtr lLoginID,
uint dwCommand,
int lChannel,
out NET_TIME lpOutBuffer,
uint dwOutBufferSize,
out uint lpBytesReturned,
int waittime
);
The main problems that I can see are that:
You are translated dwOutBufferSize incorrectly. It's an IN parameter but you are passing it by reference. This is the most likely explanation for the failure.
In the C++ code you pass a pointer to a DWORD variable for lpBytesReturned. In your C# code you pass IntPtr.Zero which is the null pointer.
So, I'd have the call to CLIENT_GetDevConfig looking like this:
NET_TIME nt;
uint sizeofnt = (uint)Marshal.SizeOf(typeof(NET_TIME));
uint BytesReturned;
if (!CLIENT_GetDevConfig(lLogin, 8, 0, out nt, sizeofnt, out BytesReturned, 500))
....
It may be that you can indeed pass IntPtr.Zero to the BytesReturned parameter. Perhaps it's an optional parameter. But I cannot tell that from here. However, for sure the dwOutBufferSize mis-declaration is an error.
For learning purposes, I want to port some C code to C#. I already ported some code, but this one gives me major headaches. How do I convert this code to C#?
typedef enum
{
PXA_I2C_FAST_SPEED = 1,
PXA_I2C_NORMAL_SPEED
} PXA_I2C_SPEED_T;
typedef enum
{
I2C_OPCODE_READ = 1,
I2C_OPCODE_WRITE = 2,
I2C_OPCODE_READ_ONESTOP = 3,
I2C_OPCODE_WRITE_ONESTOP = 4,
} PXA_I2C_OPERATION_CODE;
typedef struct
{
/* input: */
DWORD mTransactions;
PXA_I2C_SPEED_T mClkSpeed;
UCHAR mDeviceAddr; //7 bit
PXA_I2C_OPERATION_CODE *mOpCode;
DWORD *mBufferOffset;
DWORD *mTransLen;
/* output: */
//DWORD mErrorCode;
UCHAR *mBuffer;
} PXA_I2CTRANS_T;
Then somewhere later the struct PXA_I2CTRANS_T is used with DeviceIoControl like this:
DeviceIoControl (hDevice, IOCTL_I2C_TRANSACT, NULL, 0, pTrans, sizeof(PXA_I2CTRANS_T), &BytesWritten, NULL);
Do I have to use IntPtr?
Do I have to shift the ClockSpeed into the DeviceAddress (because DeviceAddress is supposed to be 7 bits, but in C# it's 8 bits)?
And why is the struct used like an output buffer, when it is clearly something to send (with reserved memory to store the output, too)?
All I have now is this:
[DllImport("coredll.dll", SetLastError = true)]
private static extern bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
IntPtr InBuffer,
uint nInBufferSize,
[In, Out] IntPtr OutBuffer,
uint nOutBufferSize,
IntPtr pBytesReturned,
IntPtr lpOverlapped);
public enum Speed
{
Fast = 1,
Slow
}
public enum OperationCode
{
Read = 1,
Write = 2,
ReadOneStop = 3,
WriteOneStop = 4
}
[StructLayout(LayoutKind.Sequential)]
public struct TransactionData
{
public uint Transactions;
public I2cDevice.Speed ClockSpeed;
public byte DeviceAddress;
public IntPtr OpCode;
public IntPtr BufferOffset;
public IntPtr TransactionLength;
public IntPtr Buffer;
}
Later I pinned byte arrays to the structure and marshalled it, so I can do this:
TransactionData data = new TransactionData();
//declaring some arrays, allocating memory and pinning them to the struct
//also filling the non pointer fields with data
GCHandle handle1 = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr p = handle1.AddrOfPinnedObject();
DeviceIoControl(Handle, CtrlCode.Transact, IntPtr.Zero, 0, p, (uint)Marshal.SizeOf(typeof(TransactionData)), bytesreturned, IntPtr.Zero);