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.
Related
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 am using a c# wrapper, in the c++ library, the called function returns a pointer to the class object.
In the c# wrapper, if I call that method it returns an interface variable.
That interface variable is null, so I am unable gets the values.
How should I handle that interface variable in order to get values.
Anyone please help me.
In the below code we have ROOTNET.Interface.NTH1F it is an interface, where ROOTNET.NTH1F is a class
using ROOTNET.Utility;
using ROOTNET.Interface;
NTH1F g = new ROOTNET.NTH1F("g", "background removal", doubleArrayX.Length - 1,
doubleArrayX);
g.SetContent(doubleArrayY);
g.GetXaxis().SetRange(xmin, xmax);
ROOTNET.NTH1F bkg = new ROOTNET.NTH1F(g);
bkg.Reset();
bkg.Add(g.ShowBackground(80, ""));
In the above Im expecting the backgroung removed values to be saved in bkg but bkg contains all zeros, can you please help me in getting background removed values of g into bkg.
Where as the code of ShowBackground(int niter, string option) method is
public unsafe virtual NTH1 ShowBackground (int niter, string option)
{
NetStringToConstCPP netStringToConstCPP = null;
NetStringToConstCPP netStringToConstCPP2 = new NetStringToConstCPP (option);
NTH1 bestObject;
try
{
netStringToConstCPP = netStringToConstCPP2;
int num = *(int*)this._instance + 912;
bestObject = ROOTObjectServices.GetBestObject<NTH1> (calli ((), this._instance, niter, netStringToConstCPP.op_Implicit (), *num));
}
catch
{
((IDisposable)netStringToConstCPP).Dispose ();
throw;
}
((IDisposable)netStringToConstCPP).Dispose ();
return bestObject;
}
You cannot treat a pointer value returned from C++ as an interface (unless it's a COM interface, I guess). C++ and C# classes and interfaces may (and mostly probably do) have different low-level structures, so you cannot simply cast one onto another.
The only way is to write another wrapper around C++ class returned by your library. It should look more less like that:
C++/DLL:
__declspec(dllexport) void * ReturnInstance()
{
return new MyClass();
}
__declspec(dllexport) void MyClass_CallMethod(MyClass * instance)
{
instance->Method();
}
C#:
[DllImport("MyDll.dll")]
private static extern IntPtr ReturnInstance();
class MyClassWrapper
{
private IntPtr instance;
[DllImport("MyDll.dll")]
private static extern void MyClass_CallMethod(IntPtr instance);
public MyClassWrapper(IntPtr newInstance)
{
instance = newInstance;
}
public void Method()
{
MyClass_CallMethod(instance);
}
}
// (...)
IntPtr myClassInstance = ReturnInstance();
MyClassWrapper wrapper = new MyClassWrapper(myClassInstance);
wrapper.Method();
Hope this helps.
I am tired of writing:
if(objectA!=null)
return;
or:
if(objectB==null)
return;
So I was hope to shorten this snippet, to something like this:
Returns.IfNull(objectA);
it is pretty match the same length but usually there are few objects to check and adding params as parameter can shorten:
if(objectA==null || objectB!=null || objectC!=null)
return;
to:
Returns.IfNull(objectA,objectB,objectC);
Basically function IfNull have to get access to function one step higher in stack trace and finish it. But that's only idea, I don't know if it's even possible. Can I find simililar logic in some lib?
No, you are essentially asking the function to exit the function higher than itself which isn't desirable nor really possible unless you throw an exception (which isn't returning per se).
So, you can either do your simple and concise if-null-return checks, or what you may want to do there instead is to throw a well defined exception, but I don't recommend exceptions for flow-control. If these are exceptional (error) circumstances, though, then consider throwing an ArgumentNullException() and handling it as appropriate.
You could write some helper methods to throw ArgumentNullException() for you, of course, to clean it up a bit:
public static class ArgumentHelper
{
public static void VerifyNotNull(object theObject)
{
if (theObject == null)
{
throw new ArgumentNullException();
}
}
public static void VerifyNotNull(params object[] theObjects)
{
if (theObjects.Any(o => o == null))
{
throw new ArgumentNullException();
}
}
}
Then you could write:
public void SomeMethod(object obj1, object obj2, object obj3)
{
ArgumentHelper.VerifyNotNull(obj1, obj2, obj3);
// if we get here we are good!
}
But once again, this is exceptions and not a "return" of the previous method in the stack, which isn't directly possible.
You are asking for something that only the language designer can fix for you.
I have proposed one thing by myself.
The .? operator does return from the current method with the default return value when the argument left to it is null.
return appSettings.?GetElementKey(key).?Value ?? "";
Perhaps we will see it some day in C# 6?
To do similar comparison checks I once defined the following extension method:
/// <summary>
/// Returns whether the object equals any of the given values.
/// </summary>
/// <param name = "source">The source for this extension method.</param>
/// <param name = "toCompare">The objects to compare with.</param>
/// <returns>
/// True when the object equals any of the passed objects, false otherwise.
/// </returns>
public static bool EqualsAny( this object source, params object[] toCompare )
{
return toCompare.Any( o => o.Equals( source ) );
}
It can simplify redundant checks, e.g.:
string someString = "bleh";
bool anyEquals = someString.EqualsAny( "bleh", "bloeh" );
In your case where you check for multiple null checks you could use it as follows:
if ( EqualsAny( null, objectA, objectB, objectX ) ) return;
On another note, your code reminds me of Code Contracts which allows you to define pre and post conditions. In case this is your scenario - perhaps not as I don't see why you call return - it might interest you. Part of it is available for free in .NET 4.0.
You can not invoke another method and expect it to return to the callee of the current method (you could if we had something like continuation passing style; alas, we do not).
You could say:
if(new[] { objectA, objectB, objectC }.Any(x => x != null)) {
return;
}
Or:
if(new[] { objectA, objectB, objectC }.AnyAreNotNull()) {
return;
}
Here, AnyAreNotNull is:
public static class EnumerableExtensions {
public static bool AnyAreNotNull<T>(this IEnumerable<T> source) {
Contract.Requires(source != null);
return source.Any(x => x != null);
}
}
But really, there is nothing wrong with just writing the usual code for this situation.
No, a method can't return the method above it.
Best you could do is create a method that returned true if any of its params were null, then do if (ReturnHelper.AllNull(obj1, obj2, obj3)) return; but i'd say this is much less readable.
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);
}
}
}
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.