Is C# able to define macros as is done in the C programming language with pre-processor statements? I would like to simplify regular typing of certain repeating statements such as the following:
Console.WriteLine("foo");
No, C# does not support preprocessor macros like C. Visual Studio on the other hand has snippets. Visual Studio's snippets are a feature of the IDE and are expanded in the editor rather than replaced in the code on compilation by a preprocessor.
You can use a C preprocessor (like mcpp) and rig it into your .csproj file. Then you chnage "build action" on your source file from Compile to Preprocess or whatever you call it.
Just add BeforBuild to your .csproj like this:
<Target Name="BeforeBuild" Inputs="#(Preprocess)" Outputs="#(Preprocess->'%(Filename)_P.cs')">
<Exec Command="..\Bin\cpp.exe #(Preprocess) -P -o %(RelativeDir)%(Filename)_P.cs" />
<CreateItem Include="#(Preprocess->'%(RelativeDir)%(Filename)_P.cs')">
<Output TaskParameter="Include" ItemName="Compile" />
</CreateItem>
You may have to manually change Compile to Preprocess on at least one file (in a text editor) - then the "Preprocess" option should be available for selection in Visual Studio.
I know that macros are heavily overused and misused but removing them completely is equally bad if not worse. A classic example of macro usage would be NotifyPropertyChanged. Every programmer who had to rewrite this code by hand thousands of times knows how painful it is without macros.
I use this to avoid Console.WriteLine(...):
public static void Cout(this string str, params object[] args) {
Console.WriteLine(str, args);
}
and then you can use the following:
"line 1".Cout();
"This {0} is an {1}".Cout("sentence", "example");
it's concise and kindof funky.
While you can't write macros, when it comes to simplifying things like your example, C# 6.0 now offers static usings. Here's the example Martin Pernica gave on his Medium article:
using static System.Console; // Note the static keyword
namespace CoolCSharp6Features
{
public class Program
{
public static int Main(string[] args)
{
WriteLine("Hellow World without Console class name prefix!");
return 0;
}
}
}
There is no direct equivalent to C-style macros in C#, but inlined static methods - with or without #if/#elseif/#else pragmas - is the closest you can get:
/// <summary>
/// Prints a message when in debug mode
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void Log(object message) {
#if DEBUG
Console.WriteLine(message);
#endif
}
/// <summary>
/// Prints a formatted message when in debug mode
/// </summary>
/// <param name="format">A composite format string</param>
/// <param name="args">An array of objects to write using format</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void Log(string format, params object[] args) {
#if DEBUG
Console.WriteLine(format, args);
#endif
}
/// <summary>
/// Computes the square of a number
/// </summary>
/// <param name="x">The value</param>
/// <returns>x * x</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Square(double x) {
return x * x;
}
/// <summary>
/// Wipes a region of memory
/// </summary>
/// <param name="buffer">The buffer</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void ClearBuffer(ref byte[] buffer) {
ClearBuffer(ref buffer, 0, buffer.Length);
}
/// <summary>
/// Wipes a region of memory
/// </summary>
/// <param name="buffer">The buffer</param>
/// <param name="offset">Start index</param>
/// <param name="length">Number of bytes to clear</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void ClearBuffer(ref byte[] buffer, int offset, int length) {
fixed(byte* ptrBuffer = &buffer[offset]) {
for(int i = 0; i < length; ++i) {
*(ptrBuffer + i) = 0;
}
}
}
This works perfectly as a macro, but comes with a little drawback: Methods marked as inlined will be copied to the reflection part of your assembly like any other "normal" method.
Luckily, C# has no C/C++-style preprocessor - only conditional compilation and pragmas (and possibly something else I cannot recall) are supported. Unfortunatelly, C# has no metaprogramming capabilities (this may actually relate to your question to some extent).
Turn the C Macro into a C# static method in a class.
I would suggest you to write extension, something like below.
public static class WriteToConsoleExtension
{
// Extension to all types
public static void WriteToConsole(this object instance,
string format,
params object[] data)
{
Console.WriteLine(format, data);
}
}
class Program
{
static void Main(string[] args)
{
Program p = new Program();
// Usage of extension
p.WriteToConsole("Test {0}, {1}", DateTime.Now, 1);
}
}
Hope this helps (and not too late :) )
Use lambdas
void print(string x) => Trace.WriteLine(x);
void println(string x) => Console.WriteLine(x);
void start(string x) => Process.Start(x);
void done() => Trace.WriteLine("Done");
void hey() => Console.WriteLine("hey");
Since C# 7.0 supports using static directive and Local functions you don't need preprocessor macros for most cases.
Related
I use an XOR based implementation in the GetHashCode implementation of most of my equatable types.
I've read several posts explaining why it is not the best solution so I decided to implement GetHashCode as suggested by Jon Skeet:
unchecked // Overflow is fine, just wrap
{
int hash = 17;
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
}
Since the code is likely to be similar in most implementations, I tried to build a helper class to calculate hash codes for all my classes. It should be an easy thing to do but one of the main constraints with GetHashCode is it has to be fast. Therefore any implementation involving allocation is probably a no go (for instance, the use of a non static class).
Ideally a call to such a method would look like:
public override GetHashCode() => HashCodeCalculator.Calculate(X, Y, Z);
And have all the logic (unchecked + primes + null check...). But the use of a params parameter implicitly creates an array.
Is it best to duplicate the hashing algorithm in each class instead? Or is a class like the following as efficient?
public static class HashCalculator
{
private const int _seed = 5923;
private const int _multiplier = 7481;
public static int Add(object value) => Add(_seed, value);
public static int Add(int current, object value)
{
int valueHashCode = (value != null) ? value.GetHashCode() : 0;
unchecked
{
return (current * _multiplier) + valueHashCode;
}
}
}
which can then be used like this:
public override int GetHashCode()
{
int result = HashCalculator.Add(Prop1);
result = HashCalculator.Add(result, Prop2);
return result;
}
You can create overloads for various small fixed numbers of parameters (2, 3, 4, etc. until you decide to stop), in order to avoid the array allocation, and then have a params overload that only ever needs to be used when there is a particularly large number of operands, at which point the overhead of the array allocation is less likely to be a problem (as it'll be a smaller percentage of the work done).
I can see why it is so tempting to have some kind of helper tool to calc hashes, but in this case efficiency is in great contradiction to convenience. You are trying to have a cookie and eat it and the answer depends on how much cookie you are willing to left over :)
One additional method call? Then it should have signature simmilar to
int HashCode(params int subhashcodes)
but invoking it will be ugly because you need to provide hashcodes of fields as parameters.
One method call and boxing? Then you can change int to object in previous signature to call fields hashcodes inside your method (I'm not fully sure that there will be no boxing in first case - feel free to correct me)
Personally I will stick to writing it by hand (or by Resharper).
After benchmarking it appears that using a struct like the following is almost as efficient as XORing and nicely encapsulates hash codes calculation.
/// <summary>
/// Calculates a hash code based on multiple hash codes.
/// </summary>
public struct HashCode
{
private const int _seed = 5923;
private const int _multiplier = 7481;
/// <summary>
/// Builds a new hash code.
/// </summary>
/// <returns>The built hash code.</returns>
public static HashCode Build() => new HashCode(_seed);
/// <summary>
/// Constructor from a hash value.
/// </summary>
/// <param name="value">Hash value.</param>
private HashCode(int value)
{
_value = value;
}
/// <summary>
/// Builds a new hash code and initializes it from a hash code source.
/// </summary>
/// <param name="hashCodeSource">Item from which a hash code can be extracted (using GetHashCode).</param>
public HashCode(object hashCodeSource)
{
int sourceHashCode = GetHashCode(hashCodeSource);
_value = AddValue(_seed, sourceHashCode);
}
private readonly int _value;
/// <summary>
/// Returns the hash code for a given hash code source (0 if the source is null).
/// </summary>
/// <param name="hashCodeSource">Item from which a hash code can be extracted (using GetHashCode).</param>
/// <returns>The hash code.</returns>
private static int GetHashCode(object hashCodeSource) => (hashCodeSource != null) ? hashCodeSource.GetHashCode() : 0;
/// <summary>
/// Adds a new hash value to a hash code.
/// </summary>
/// <param name="currentValue">Current hash value.</param>
/// <param name="valueToAdd">Value to add.</param>
/// <returns>The new hash value.</returns>
private static int AddValue(int currentValue, int valueToAdd)
{
unchecked
{
return (currentValue * _multiplier) + valueToAdd;
}
}
/// <summary>
/// Adds an object's hash code.
/// </summary>
/// <param name="hashCode">Hash code to which the object's hash code has to be added.</param>
/// <param name="hashCodeSource">Item from which a hash code can be extracted (using GetHashCode).</param>
/// <returns>The updated hash instance.</returns>
public static HashCode operator +(HashCode hashCode, object hashCodeSource)
{
int sourceHashCode = GetHashCode(hashCodeSource);
int newHashValue = AddValue(hashCode._value, sourceHashCode);
return new HashCode(newHashValue);
}
/// <summary>
/// Implicit cast operator to int.
/// </summary>
/// <param name="hashCode">Hash code to convert.</param>
public static implicit operator int(HashCode hashCode) => hashCode._value;
}
which can be used like this:
public override int GetHashCode() => new HashCode(Prop1) + Prop2;
EDIT:
.net core now has such a HashCode struct.
I'm trying to implement managed debugger looking at MDBG sample.
MDBG is capable of resolving function names within given scope, but it's not taking in consideration base classes.
MDBG is doing this:
/// <summary>
/// Resolves a Function from a Module, Class Name, and Function Name.
/// </summary>
/// <param name="mdbgModule">The Module that has the Function.</param>
/// <param name="className">The name of the Class that has the Function.</param>
/// <param name="functionName">The name of the Function.</param>
/// <returns>The MDbgFunction that matches the given parameters.</returns>
public MDbgFunction ResolveFunctionName(MDbgModule mdbgModule, string className, string functionName) {
...
foreach (MethodInfo mi in t.GetMethods()) {
if (mi.Name.Equals(functionName)) {
func = mdbgModule.GetFunction((mi as MetadataMethodInfo).MetadataToken);
break;
}
}
return func;
}
While the Type.GetMethods() is overriden and has this implementation, using IMetaDataImport.EnumMethods:
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) {
ArrayList al = new ArrayList();
IntPtr hEnum = new IntPtr();
int methodToken;
try {
while (true) {
int size;
m_importer.EnumMethods(ref hEnum, (int) m_typeToken, out methodToken, 1, out size);
if (size == 0) {
break;
}
al.Add(new MetadataMethodInfo(m_importer, methodToken));
}
}
finally {
m_importer.CloseEnum(hEnum);
}
return (MethodInfo[]) al.ToArray(typeof (MethodInfo));
}
The problem is that m_importer.EnumMethods() Enumerates MethodDef tokens representing methods of the specified type, but I'm interested in all methods from the class hierarchy.
How can I get all the Methods defined in class hierarchy? (Obviously, common methods like reflection cannot be used, since I'm analyzing type defined in other process)
My limited knowledge of interop and deep CLR/CIL structure creates impediments for finding the right way to go here.
Any advice/suggestion is welcome!
Regards,
GetTypeProps will return the metadata token of the base type in ptkExtends, you can use that to walk up the inheritance tree and collect the methods from each as you go.
Be aware, however, that the metadata token might not be a TypeDef. It could be a TypeRef (requiring you to resolve the type) or a TypeSpec (requiring you to parse the type signature and extract an appropriate TypeDef/TypeRef).
I'm writing a wrapper for a C dll. Various C functions are wrapped for C# applicatons. Now consider some simplified part of the wrapper below.
public enum ErrorCode
{
OK = 0,
...
...
}
public class AppException: ApplicationException
{
public AppException(ErrorCode errorCode) : base()
{
error = errorCode;
}
public ErrorCode error { get; private set; }
}
public class A
{
public ErrorCode last_ret;
private IntPtr datap;
public A(string filename)
{
last_ret = (ErrorCode)ClibDllFunc1(filename, out datap);
if (last_ret != ErrorCode.OK)
throw new AppException(last_ret);
// go on processing
last_ret = (ErrorCode)ClibDllFunc2(datap);
if (last_ret != ErrorCode.OK)
throw new AppException(last_ret);
}
public void getSize(out int sz)
{
last_ret = (ErrorCode)ClibDllFunc3(datap, out sz);
if (last_ret != ErrorCode.OK)
throw new AppException(last_ret);
}
// ...
// many functions like these, all working by calling c/c++ dll functions
// with different number and types of parameters
}
[DllImport("clibrary.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
static extern internal int ClibDllFunc1(string filename, out IntPtr data);
// ... other C function declarations follow similarly
As you can see, the wrapper calls various C functions. All C functions return integer as the status code (an ErrorCode), and the wrapper has to check this return code and throw an application defined exception if the C function fails. This has to be done exactly the same way for all C function calls. Only the function name and parameters change but the 3 line calling-block is the same. It looks really cheap in this form as copy/pasted 3-line blocks of function calls.
In C#, is there a way to simplify and encapsulate the "call, check return code, throw exception" cycle in a simpler and more compact way?
For reference (actually this is what I'd like to do to simplify the calls); in C/C++ we can define a macro like this one:
#define SAFE_CALL(call) do{ if((last_ret = (ErrorCode)call) != OK) throw AppException(last_ret); }while(0)
and call like this:
SAFE_CALL(ClibDllFunc1(filename, &datap));
SAFE_CALL(ClibDllFunc2(datap));
SAFE_CALL(ClibDllFunc3(datap, &sz));
Edit
Rereading your problem, I answered the wrong question. What you really want is a function CheckErrorCode that takes an int, and then simply pass the result of the native call.
/// <summary>
/// Takes the result code from invoking a native function. If the result is
/// not ErrorCode.OK, throws an AppException with that error code.
/// </summary>
/// <param name="returnCodeInt">
/// The return code of a native method call, as an integer.
/// Will be cast to ErrorCode.
/// </param>
private static void CheckErrorCode(int returnCodeInt)
{
ErrorCode returnCode = (ErrorCode)returnCodeInt;
if(returnCode != ErrorCode.OK)
{
throw new AppException(returnCode);
}
}
public void getSize(out int sz)
{
CheckErrorCode(ClibDllFunc3(datap, out sz));
}
Original text (how to simulate macros with lambdas)
The fact that lambda syntax in C# is so terse means you can use a Func<T> in a similar way to macros. Try something like this:
/// <summary>
/// Calls a function's native implementation, then checks if the error code
/// is not ErrorCode.Ok. If it is, throws an AppException.
/// </summary>
/// <param name="nativeCall">
/// A function that returns the status code as an int.
/// </param>
private static void CheckErrorCode(Func<int> nativeCall)
{
var returnCode = (ErrorCode)nativeCall();
if(returnCode != ErrorCode.OK)
{
throw new AppException(returnCode);
}
}
You can then call it with:
public void getSize(out int sz)
{
// drawback: compiler can't check that sz is always written.
sz = 0;
CheckErrorCode(() => ClibDllFunc3(datap, out sz));
}
The lambda creates what's known as a closure. This is a way to pull the logic of calling ClibDllFunc3 (specific to this function) away from the logic of handling its results (which is standard across all your DLL functions). Unlike many closures, this one is called immediately.
I'm trying to implement my own solution for logging. Everything works fine except one thing, that just doesn't want to work out.
I have a class (Log), which has methods to log to file etc.
I can use it like Log.Debug(message, args), but thats not enough for me.
Sadly in C# we can't overload the call operator to be able to do something like Log(message, args).
Therefore I've searched on the web and found out about the indexer.
My idea would be now to do something like:
Log[loggingMode](message, args).
But I just can't get it working. I currently have delegate, a method and the indexer, which look like this:
/// <summary>
/// Delegate for logging function, used by the indexer.
/// </summary>
/// <param name="mode">The logging mode.</param>
/// <param name="message">The message to log.</param>
/// <param name="args">The args for the message (String.Format).</param>
public delegate void LogDelegate(string mode, string message, params object[] args);
public LogDelegate this[string mode]
{
get
{
return LogIndexer;
}
}
public void LogIndexer(string mode, string message, params object[] args)
{
lock (_Lock)
{
_queue.Enqueue(new LogEntry(String.Format(message, args), mode));
}
}
Now my question is, how can I pass the one argument of the indexer (mode) to the function, so that I can call it like:
Log"debug";
this[string mode] getter should use its mode parameter to return a lambda with this mode:
public delegate void LogDelegate(string message, params object[] args);
public LogDelegate this[string mode]
{
get
{
return (message, args) => LogIndexer(mode, message, args);
}
}
I have an external library that takes an IntPtr. Is there any safe way to do this...
int BytesWritten = 0;
Output.WriteBytes(buffer, new IntPtr(&BytesWritten));
...without having to use 'unsafe' code? I'm not that familiar with IntPtrs, but I'd like to do something like this:
fixed int BytesWritten = 0;
Output.WriteBytes(buffer, IntPtr.GetSafeIntPtr(ref BytesWritten));
...in such a way that I don't need to compile with /unsafe.
I can't change the WriteBytes function, it's an external function.
It seems like there should be some sort of cast between 'ref int' and IntPtr, but I have not had luck finding it.
I assume that Output.WriteBytes is a [DllImport] method. Can you post the declaration?
You should be able to avoid the pointer by declaring the last parameter as out int instead of IntPtr -- let the P/Invoke marshaller do the rest.
Yes, there is. You can use P/Invoke for your code. It will create the pointer for you automagically. Something like this:
[DllImport("yourlib", SetLastError=true)]
static extern bool WriteBytes(
[MarshalAs(UnmanagedType.LPArray)]
byte [] buffer,
ref int BytesWritten);
(I added the array as a bonus). More info on P/Invoke can be found, with gazillion examples, at pinvoke.net.
Each parameter above can take out, in and ref. Out and ref parameters are translated as pointers, where an ref-parameter is two-way.
Here is a class that will provide you with a safe IntPtr implementation. It derives from the SafeHandleZeroOrMinusOneIsInvalid class, provided by the .NET framework.
/// <summary>
/// IntPtr wrapper which can be used as result of
/// Marshal.AllocHGlobal operation.
/// Call Marshal.FreeHGlobal when disposed or finalized.
/// </summary>
class HGlobalSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// Creates new instance with given IntPtr value
/// </summary>
public HGlobalSafeHandle(IntPtr ptr) : base(ptr, true)
{
}
/// <summary>
/// Creates new instance with zero IntPtr
/// </summary>
public HGlobalSafeHandle() : base(IntPtr.Zero, true)
{
}
/// <summary>
/// Creates new instance which allocates unmanaged memory of given size
/// Can throw OutOfMemoryException
/// </summary>
public HGlobalSafeHandle(int size) :
base(Marshal.AllocHGlobal(size), true)
{
}
/// <summary>
/// Allows to assign IntPtr to HGlobalSafeHandle
/// </summary>
public static implicit operator HGlobalSafeHandle(IntPtr ptr)
{
return new HGlobalSafeHandle(ptr);
}
/// <summary>
/// Allows to use HGlobalSafeHandle as IntPtr
/// </summary>
public static implicit operator IntPtr(HGlobalSafeHandle h)
{
return h.handle;
}
/// <summary>
/// Called when object is disposed or finalized.
/// </summary>
override protected bool ReleaseHandle()
{
Marshal.FreeHGlobal(handle);
return true;
}
/// <summary>
/// Defines invalid (null) handle value.
/// </summary>
public override bool IsInvalid
{
get
{
return (handle == IntPtr.Zero);
}
}
}