C# How to define new pointer struct? - c#

This structure is define at http://msdn.microsoft.com/en-us/library/windows/hardware/ff541621%28v=vs.85%29.aspx
typedef struct _FILTER_MESSAGE_HEADER {
ULONG ReplyLength;
ULONGLONG MessageId;
} FILTER_MESSAGE_HEADER, *PFILTER_MESSAGE_HEADER;
I defined it in C# code as below:
[StructLayout(LayoutKind.Sequential)]
public struct FILTER_MESSAGE_HEADER {
public uint replyLength;
public ulong messageId;
};
I only define FILTER_MESSAGE_HEADER in C# code, PFILTER_MESSAGE_HEADER isn't.
How should I do to define PFILTER_MESSAGE_HEADER??
P/S: I want to define PFILTER_MESSAGE_HEADER to use this struct in a function.

You don't have to (can't) define PFILTER_MESSAGE_HEADER. Just specify it as either out or ref as appropriate.
[DllImport("foo")]
void SomeMethod(ref FILTER_MESSAGE_HEADER lpMessageBuffer);
If you are specifically interested in FilterGetMessage, I'm not sure what if any dll it is exported from, but one possible signature would be as below:
[DllImport(fltmgr, CharSet=CharSet.Unicode, ExactSpelling=true, PreserveSig=false)]
void FilterGetMessage(
CommunicationPortSafeHandle hPort,
ref FILTER_MESSAGE_HEADER lpMessageBuffer,
uint dwMessageBufferSize,
IntPtr lpOverlapped);
I used PreserveSig to automatically translate the HRESULT to an exception in the event of failure, the CharSet specification is defensive and results in the need for ExactSpelling. CommunicationPortSafeHandle would be a class which inherits from SafeHandleMinusOneIsInvalid based off of the documentation on FilterConnectCommunicationPort.
You would use this signature as:
FILTER_MESSAGE_HEADER header;
FilterGetMessage(hFilter, ref header,
Marshal.SizeOf(typeof(FILTER_MESSAGE_HEADER)), IntPtr.Zero);

Related

Passing different type of objects to unmanaged function

First: I'm sorry if the title is wrong. I'm not sure how to name my problem.
In my C API I have a function:
MYAPI_STATUS SetParam(void *hInst, unsigned long param, void *value);
This function accepts different types of pointers depending on param type. Like this:
SetParam(hInst, 1, (void*)"somevalue");
int x = 55;
SetParam(hInst, 2, &x);
I'm just writing a wrapper/binding in C# and I have a problem.
[DllImport("myapi", CallingConvention = CallingConvention.Cdecl]
public static extern uint SetParam(IntPtr hInst, uint paramCode, IntPtr paramValue);
What's the best way to replicate behaviour from C? So the function would look like:
public static uint SetParam(IntPtr hInst, uint paramCode, ref object paramValue);
or possibly:
public static uint SetParam(IntPtr hInst, uint paramCode, object paramValue);
I solved it by marshalling manually first checking type of object if the object is string then I use Marshal.StringToHGlobalAnsi if it's something else then I marshall differently based on what I need.
If someone has any better solution feel free to write :)
The * sign in C programming means give parameter by reference, so this code is not match:
public static uint SetParam(IntPtr hInst, uint paramCode, object paramValue);
Because it gives parameter by value.
This code is very similar to what you want:
public static uint SetParam(IntPtr hInst, uint paramCode, ref object paramValue);
But there is a bit difference. When you using ref before a parameter you have to initialize it before sending to the method, but by using out you don't have this limitation for passing it. So I think the best possible match will be this code:
public static uint SetParam(IntPtr hInst, uint paramCode, out object paramValue);

Structure alignment in C#

I am working with SQL VDI and attempting to pass a structure from C# to C++ via a COM interface. The structure is defined in the C++ header as:
#pragma pack(8)
struct VDConfig
{
unsigned long deviceCount;
unsigned long features;
unsigned long prefixZoneSize;
unsigned long alignment;
unsigned long softFileMarkBlockSize;
unsigned long EOMWarningSize;
unsigned long serverTimeOut;
unsigned long blockSize;
unsigned long maxIODepth;
unsigned long maxTransferSize;
unsigned long bufferAreaSize;
} ;
To emulate this, I have defined the structure in C# as:
[StructLayout(LayoutKind.Explicit)]
public struct VDConfig
{
[FieldOffset(0)]
public uint deviceCount;
[FieldOffset(4)]
public uint features;
[FieldOffset(8)]
public uint prefixZoneSize;
[FieldOffset(12)]
public uint alignment;
[FieldOffset(16)]
public uint softFileMarkBlockSize;
[FieldOffset(20)]
public uint EOMWarningSize;
[FieldOffset(24)]
public uint serverTimeout;
[FieldOffset(28)]
public uint blockSize;
[FieldOffset(32)]
public uint maxIODepth;
[FieldOffset(36)]
public uint maxTransferSize;
[FieldOffset(40)]
public uint bufferAreaSize;
}
I have also tried to define the structure as LayoutKind.Sequential and tried it with Pack=8. However I define the structure, when I attempt to pass it to the function, it fails and I receive the error "Alignment must be 2**n and <= system allocation granularity." I've tried defining the function that accepts the structure as:
int CreateEx([MarshalAs(UnmanagedType.LPWStr)]string instanceName,
[MarshalAs(UnmanagedType.LPWStr)]string name,
IntPtr config);
and
int CreateEx([MarshalAs(UnmanagedType.LPWStr)]string instanceName,
[MarshalAs(UnmanagedType.LPWStr)]string name,
ref VDConfig config);
I get the same result with either definition. Can anyone tell me what I'm doing wrong here?
Edit:
In looking a little closer, I'm also getting the error "Device count must be in [1..64]." I'm setting the device count to 1 and in concert with the error above, it almost looks like the function isn't getting my structure at all. Don't know if this helps or not, but maybe it'll spark something for someone.
Per request, here are the interface structures. In C++:
MIDL_INTERFACE("d0e6eb07-7a62-11d2-8573-00c04fc21759")
IClientVirtualDeviceSet2 : public IClientVirtualDeviceSet
{
public:
virtual HRESULT STDMETHODCALLTYPE CreateEx(
/* [in] */ LPCWSTR lpInstanceName,
/* [in] */ LPCWSTR lpName,
/* [in] */ struct VDConfig *pCfg) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenInSecondaryEx(
/* [in] */ LPCWSTR lpInstanceName,
/* [in] */ LPCWSTR lpSetName) = 0;
};
And my C# version:
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("d0e6eb07-7a62-11d2-8573-00c04fc21759")]
public interface IClientVirtualDeviceSet2
{
void CreateEx([In, MarshalAs(UnmanagedType.LPWStr)]string instanceName,
[In, MarshalAs(UnmanagedType.LPWStr)]string name,
[In]ref VDConfig config);
void OpenInSecondaryEx([MarshalAs(UnmanagedType.LPWStr)]string instanceName,
[MarshalAs(UnmanagedType.LPWStr)]string lpSetName);
}
For anyone else who comes across this, this is the answer:
As you can see in vdi.h, IClientVirtualDeviceSet2 "inherits" from IClientVirtualDeviceSet. As far as COM is concerned, there is no such thing as interface inheritance.
Therefore, when calling CreateEx on IClientVirtualDeviceSet2, you're actually calling Create on IClientVirtualDeviceSet (because Create is the first method in the vtable of that combined IClientVirtualDeviceSet + IClientVirtualDeviceSet2). That's why you end up getting invalid parameters.
The fix for this is to create a single interface (IClientVirtualDeviceSet2) with all the methods, IClientVirtualDeviceSet first, then the two IClientVirtualDeviceSet2 methods (obviously in order). This ensures when CreateEx() is called, it uses the correct DispId.
I'm sure you could probably use inheritance and set the DispIdAttribute accordingly:
https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dispidattribute(v=vs.110).aspx
but there is probably little point.

Passing `null` reference for a `ref struct` parameter in interop method

I am using C# to call a DLL function.
[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
pHandle handle,
ref somestruct a,
ref somestruct b);
How can I pass a null reference for argument 3?
When I try, I am getting a compile-time error:
Cannot convert from <null> to ref somestruct.
I also tried IntPtr.Zero.
You have two options:
Make somestruct a class, and change the function signature to:
[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
pHandle handle, somestruct a, somestruct b);
Usually this must not change anything else, except that you can pass a null as the value of a and b.
Add another overload for the function, like this:
[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
pHandle handle, IntPtr a, IntPtr b);
Now you can call the function with IntPtr.Zero, in addition to a ref to an object of type somestruct:
GetValue(myHandle, ref myStruct1, ref myStruct2);
GetValue(myHandle, IntPtr.Zero, IntPtr.Zero);
Since .NET 5.0 there is System.Runtime.CompilerServices.Unsafe.NullRef<T>()
GetValue(myHandle, ref myStruct1, ref myStruct2);
GetValue(myHandle, ref Unsafe.NullRef<somestruct>(), ref Unsafe.NullRef<somestruct>());
This answer suggests to make SomeStruct a class. I would like to show an implementation of that idea which appears to work nicely… even when you cannot change the definition of SomeStruct (such as when it is a predefined type like System.Guid; see also this answer).
Define a generic wrapper class:
[StructLayout(LayoutKind.Explicit)]
public sealed class SomeStructRef
{
[FieldOffset(0)]
private SomeStruct value;
public static implicit operator SomeStructRef(SomeStruct value)
{
return new SomeStructRef { value = value };
}
}
The basic idea here is identical to boxing.
Change your interop method definition to the following:
[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
pHandle handle,
ref SomeStruct a,
[MarshalAs(UnmanagedType.LPStruct)] SomeStructRef b);
The third parameter b will then be "nullable". Since SomeStructRef is a reference type, you can pass a null reference. You can also pass a SomeStruct value because an implicit conversion operator from SomeStruct to SomeStructRef exists. And (at least in theory), due to the [StructLayout]/[FieldOffset] marshalling instructions, any instance of SomeStructRef should get marshalled just like an actual instance of SomeStruct.
I'd be happy if someone who is an interop expert could validate the soundness of this techinque.
Another obvious solution is to resort to unsafe code and change the interop method declaration to this:
[DllImport("MyDLL.dll", SetLastError = true)]
unsafe public static extern uint GetValue(
pHandle handle,
ref somestruct a,
somestruct* b);
Notice that the method is now marked unsafe, and that the parameter has changed from ref somestruct to somestruct*.
This has the following implications:
The method can only be called from inside an unsafe context. For example:
somestruct s;
unsafe { GetValue(…, …, &s); } // pass a struct `s`
unsafe { GetValue(…, …, null); } // pass null reference
In order for the above to work, unsafe code must be allowed for the project (either in the project settings, or via the /unsafe command-line compiler switch).
Using unsafe leads to unverifiable IL code. IIRC, this means that loading this assembly will require full trust (which can be problematic in some situations).

Pointer to function for unmanaged code in C#

I have a dll which accepts a struct that contains a pointer to a function to do a callback.
How can I get an IntPtr to a function of my application to build the struct?
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class OPERATION {
public uint OperationID;
public IntPtr Context;
public IntPtr Callback; -> How to pass this?
}
Here is the delegate accepting the OPERATION struct
public delegate void MY_CALLBACK([In] OPERATION operation, [In] uint msgId, [In] IntPtr msgDataPtr);
use Marshal.GetFunctionPointerForDelegate
Maybe the Marshal.GetFunctionPointerForDelegate method may help you.

Parameter in C#

When I want get total value of memory in C# I found a kernel32 function in MSDN to invoke data from system. MSDN declare function this way:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
but this don't work correctly. I change "ref" to "[In, Out]" then it work correctly.
How can tell me what is [In, Out] parameters in C#?
In: http://msdn.microsoft.com/de-de/library/system.runtime.interopservices.inattribute.aspx
Out: http://msdn.microsoft.com/de-de/library/system.runtime.interopservices.outattribute.aspx
Short: They control the way data is marshalled. In this case, where you specify both of them, it means that data is marshalled to both sides (caller and callee).
The out and the ref parameters are used to return values in the same variables, ref is enough if you don't know you will use it in or out.
Out if you just want to use the variable to receive data from the function, In if you just want to send data to the function.
ref if you want to send and receive data from a function, if you put nothing so it will be In by default
Note: ref and out parameters are very useful when your method needs to return more than one values.
The following definition works (define the MEMORYSTATUSEX as a class):
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GlobalMemoryStatusEx(MEMORYSTATUSEX lpBuffer);
[StructLayout(LayoutKind.Sequential)]
public sealed class MEMORYSTATUSEX {
public uint dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
}
Usage
var status = new MEMORYSTATUSEX();
GlobalMemoryStatusEx(status);
If you look at the function definition on MSDN it will tell you whether the parameters are In/Out:
BOOL WINAPI GlobalMemoryStatusEx(
__inout LPMEMORYSTATUSEX lpBuffer
);
In general if it says out, you should use a ref parameter, it makes is easier on any future developers trying to figure out how the code is working. When looking at the function call, you know the developer meant for the argument to be affected.

Categories

Resources