Consider the following Win32 API struct:
typedef struct _SECURITY_ATTRIBUTES {
DWORD nLength;
LPVOID lpSecurityDescriptor;
BOOL bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
When porting this object to C#, should I follow the name naming conventions used here, like so:
public struct _SECURITY_ATTRIBUTES
{
public int nLength;
public unsafe byte* lpSecurityDescriptor;
public int bInheritHandle;
}
or can I go all out, and write my struct in a C# style, like so:
public struct SecurityAttributes
{
private int length;
private unsafe byte* securityDescriptor;
private int bInheritHandle;
public Int32 Length
{
get { return this.length; }
set { this.length = value; }
}
public Byte* SecurityDescriptor
{
get { return this.seurityDescriptor; }
set { this.securityDescriptor = value; }
}
public Int32 InheritHandle
{
get { return this.bInheritHandle; }
set { this.bInheritHandle = value; }
}
public SecurityAttributes(int length, byte* securityDescriptor, int inheritHandle)
{
this.length = length;
this.securityDescriptor = securityDescriptor;
this.inheritHandle = inheritHandle;
}
}
Whilst the second approach seems much more elegant, I would like to know if it is advisable to invoke native functionality using a struct written in that fashion, or if there are any other pitfalls when porting structs from C/C++.
I think this should not be a personal preference. If you are porting a code to another language, you should apply the conventions of the language that you are porting to.
I would certainly use C# conventions since the code will be used by C# developers, not C/C++ developers, right? Otherwise we would be still using ugly
_int32 DWORDlike code in C#.Here are some good guides for C# conventions: