I'm having some trouble with setting up my application to mono, it gives me a GetConsoleWindow Exception. I thought this would open a new window when you run it on windows, but in Mono, on CentOS 6 with Gnome it gives me this exception.
error code:
Unhandled Exception:
System.EntryPointNotFoundException: GetConsoleWindow
at (wrapper managed-to-native) Silverwave.Program:GetConsoleWindow ()
at Silverwave.Program.Main (System.String[] Args) [0x00000] in <filename unkno wn>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.EntryPointNotFoundException: GetConsol eWindow
at (wrapper managed-to-native) Silverwave.Program:GetConsoleWindow ()
at Silverwave.Program.Main (System.String[] Args) [0x00000] in <filename unkno wn>:0
[root#h2297404 Debug]# Unhandled Exception:
-bash: Unhandled: opdracht niet gevonden
[root#h2297404 Debug]# System.EntryPointNotFoundException: GetConsoleWindow
-bash: System.EntryPointNotFoundException:: opdracht niet gevonden
thanks in advance
Console windows are specific to Windows systems (that's why GetConsoleWindow() does not exist in .NET proper and you had to p/invoke it).
Linux systems do not expose this API, so you cannot invoke it on Linux, and there is no replacement.
Short answer - use Console.WindowWidth
Long answer:
https://unix.stackexchange.com/questions/215584/whats-the-name-of-the-environment-variable-with-current-terminal-width
$COLUMNS is one such variable.
Also there's stty -a or more specifically stty size
stty uses
get_terminal_width_height(STDIN_FILENO, &width, &height)
which in turn calls
ioctl(fd, TIOCGWINSZ, &winsize);
TIOCGWINSZ
Fill in the winsize structure pointed to by the third argument with the screen width and height.
The winsize structure is defined in `sys/ioctl.h' as follows:
struct winsize
{
unsigned short ws_row; /* rows, in characters */
unsigned short ws_col; /* columns, in characters */
unsigned short ws_xpixel; /* horizontal size, pixels */
unsigned short ws_ypixel; /* vertical size, pixels */
};
Here it is called in mono
https://github.com/mono/mono/blob/90972a343b81489e333a379e13f3e0018738e705/mono/metadata/console-unix.c#L177
exported as "TtySetup"
https://github.com/mono/mono/blob/92a0ac52a7018199f39f01625eb1025baf564743/mono/metadata/icall-def.h#L130
which is imported here to C# code
https://github.com/mono/mono/blob/88d2b9da2a87b4e5c82abaea4e5110188d49601d/mcs/class/corlib/System/ConsoleDriver.cs#L286
namespace System {
static class ConsoleDriver {
...
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern bool TtySetup (
string keypadXmit, string teardown,
out byte [] control_characters, out int *address);
Here it is called -
https://github.com/mono/mono/blob/88d2b9da2a87b4e5c82abaea4e5110188d49601d/mcs/class/corlib/System/TermInfoDriver.cs#L227
unsafe void CheckWindowDimensions ()
https://github.com/mono/mono/blob/88d2b9da2a87b4e5c82abaea4e5110188d49601d/mcs/class/corlib/System/TermInfoDriver.cs#L688
And this is available through property WindowWidth:
namespace System {
class TermInfoDriver : IConsoleDriver {
public int WindowWidth {
of interface IConsoleDriver
https://github.com/mono/mono/blob/88d2b9da2a87b4e5c82abaea4e5110188d49601d/mcs/class/corlib/System/IConsoleDriver.cs#L50
Ultimately it should be available through
https://github.com/mono/mono/blob/92a0ac52a7018199f39f01625eb1025baf564743/mcs/class/corlib/System/Console.cs#L660
I checked, this works (as of mono 4.0.2.5 at least).
using System;
class mainclass {
public static int Main(string[] args) {
Console.WriteLine(Console.WindowWidth);
return 0; } }
sabayon aa $ mcs test.cs -r:System.dll
sabayon aa $ mono test.exe
239
Related
I am practising on an online compiler. I have to write the factorial program that, given a number n from STDIN, it prints out the factorial of n to STDOUT:
I have written this
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
int result=1;
int fact = int.Parse(args[0]);
if(fact==0)
{
Console.WriteLine(result);
}
else
{
for(int i=fact;i>=1;i--)
result = i*result;
}
Console.WriteLine(result);
}
}
I know in C, we use atoi. I also tried using simple Console.ReadLine() but it simply fails the test case.
Currently, I am getting the following error -
Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Solution.Main (System.String[] args) [0x00002] in <31af8dc2b3da4d24a38e31199d9b8949>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Solution.Main (System.String[] args) [0x00002] in <31af8dc2b3da4d24a38e31199d9b8949>:0
I made a very simple program with C# VS2017 and Matlab 2012b:
namespace TestConMatlab
{
class Program
{
static void Main(string[] args)
{
try
{
var matlab = new MatlabFunction();
double[] data = { 1, 2, 3 };
double[,] r = (double[,])matlab.doMedian(data.ToArray());
Console.Out.Write("OK: " + r.ToString());
} catch( Exception ex )
{
Console.Out.Write(ex.ToString());
}
Console.ReadLine();
}
}
}
This program run on mulitple PC, but on one computer I have :
System.Exception:
... MWMCR::EvaluateFunction error ...
Undefined function 'doMedian' for input arguments of type 'double'..
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction(String functionName, Int32 numArgsOut, Int32 numArgsIn, MWArray[] argsIn)
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction(String functionName, Object[] argsIn)
at MatlabFunctionNative.MatlabFunction.doMedian(Object input)
at TestConMatlab.Program.Main(String[] args) in C:\Users\User\source\repos\TestConMatlab\Program.cs:line 18
Of course I have installed the same Matlab MCR v8.0. I have trace some API call with procmon but I did not find solution.
I have deleted the folder C:\Users\%USER%\AppData\Local\Temp\%USER%\mcrCache8.0
Remove MCR and delete manualy C:\Program Files (x86)\MATLAB, and after restart, program work !
A class which in it of itself contains its own object instantiated,when creating an object of that class in main method in c#, it gives stackoverflowExeption. Why?? I want the reason for it, not the solution.Thanks
namespace project_1
{
class check
{
check checkobject = new check();// Line-1
/*I have not access Line-1 in main method.
But due to Line-1 or Line-2, output says "Process is terminating due to StackOverflowException". Why??
I do not need the solution, I want to know the reason for it.
Removing " new check() " from Line-1, then it works fine.
*/
public void Display() {
Console.WriteLine("It worked");
}
}
class DemoProgram
{
static void Main(string[] args)
{
check ob1 = new check();// Line-2
ob1.Display();
}
}
}
This is because when you create a new check object from your main method, it triggers the initialization of the instance variable, checkobject, which again creates an object of class check. This is an infinite procedure, hence the memory alloted to your program is exhausted.
You call your class constructor every time the class is initialised. The line marked as line 1 is the one you shouldn't have. It means you call your constructor recursively.
If you try to debug your program, you see the similar output to the following. If you know almost nothing why it happens, at least you can guess something is wrong subject to the constructor.
Compilation succeeded - 1 warning(s)
jdoodle.cs(5,11): warning CS0414: The private field `check.checkobject' is assigned
but its value is never used
Stack overflow: IP: 0x5647646e1705, fault addr: 0x7fffc422eff8
Stacktrace:
at <unknown> <0xffffffff>
at (wrapper alloc) object.AllocSmall (intptr,intptr) <0x00103>
<...>
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
........
........
........
........
........
at check..ctor () [0x00000] in <db1fd2bd96e041fab014c4ec28898e03>:0
output Limit reached.
Your problem is an endless recursion caused by a field initializer.
Example
public class Test
{
Type FieldName = SomeValue;
A field initializer is executed before constructor bodies. The important take-home point here is, they are always executed.
Which means you can't do this, it runs when the class initialises.
check checkobject = new check();
Every time you new up (initialise) this class, it's going to run the above code, which by its very nature new's up another instances of itself due to the *field initializers, which in-turns runs the above again so-on-and-so-forth until you run out of stack.
If you really want a self-referencing property like this, and you want it initialised (in an automatic sense), use a lazy loading technique, eg.
private Check _checkObject;
public Check CheckObject => _checkObject?? (_checkObject = new Check());
I am developing a Kinect based gesture recognizing application on Unity3D. I have to utilize an algorithm that has been written in Matlab. Thus I decided to generate a .Net DLL with Matlab deploytool and I successfully did so. Then I tested the DLL in a standalone .Net application project(in Visual Studio 2017) where it worked perfectly. BUT, when I turned to Unity3D, that DLL never worked...... What I got is shown as below:
enter image description here
System.TypeInitializationException: An exception was thrown by the type initializer for Untitled1.ADD ---> System.NotImplementedException: The requested feature is not implemented.
at System.Security.Principal.WindowsIdentity.GetCurrent (Boolean ifImpersonating) [0x00000] in /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Security.Principal/WindowsIdentity.cs:166
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction (System.String functionName, Int32 numArgsOut, Int32 numArgsIn, MathWorks.MATLAB.NET.Arrays.MWArray[] argsIn) [0x00000] in <filename unknown>:0
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction (Int32 numArgsOut, System.String functionName, MathWorks.MATLAB.NET.Arrays.MWArray[] argsIn) [0x00000] in <filename unknown>:0
at MathWorks.MATLAB.NET.Utility.MWMCR.setBuilderUserData () [0x00000] in <filename unknown>:0
at MathWorks.MATLAB.NET.Utility.MWMCR..ctor (System.String componentId, System.String componentPath, System.IO.Stream embeddedCtfStream, Boolean isLibrary) [0x00000] in <filename unknown>:0
at Untitled1.ADD..cctor () [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at dlltest.Start () [0x00000] in E:\Unity\mPrj\Assets\dlltest.cs:40
UnityEngine.Debug:Log(Object)
dlltest:Start() (at Assets/dlltest.cs:46)
From the Log, it seemed that the initializing of MCR was failed, but I just can not find why after viewing the C# source code generated by Matlab(who ever has done this job before must know what I am talking about).
Is there someone who is experienced in this kind of work and can explain to me this happened and how to solve? Thank you so much!
The namespace of the DLL is Untitled1(got no time to give it a name...) and the name of the class in the DLL is ADD.
Followings are the related code in this process(test samples):
Matlab source code add.m:
function y = add(n,m)
y = n+m;
The C# Code, which is generated by Matlab during building the M file into DLL, is too long to paste here, so I just show the code that defines the constructor, at which the error in Unity3D happen according to the Log:
static ADD()
{
if (MWMCR.MCRAppInitialized)
{
Assembly assembly= Assembly.GetExecutingAssembly();
string ctfFilePath= assembly.Location;
int lastDelimiter= ctfFilePath.LastIndexOf(#"\");
ctfFilePath= ctfFilePath.Remove(lastDelimiter, (ctfFilePath.Length - lastDelimiter));
string ctfFileName = "Untitled1.ctf";
Stream embeddedCtfStream = null;
String[] resourceStrings = assembly.GetManifestResourceNames();
foreach (String name in resourceStrings)
{
if (name.Contains(ctfFileName))
{
embeddedCtfStream = assembly.GetManifestResourceStream(name);
break;
}
}
mcr= new MWMCR("",
ctfFilePath, embeddedCtfStream, true);
}
else
{
throw new ApplicationException("MWArray assembly could not be initialized");
}
}
The code that successfully used the DLL in a standalone .Net Application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
using Untitled1;
namespace AddDllTest
{
class Program
{
static void Main(string[] args)
{
ADD myAdd = new ADD();
Console.WriteLine(myAdd.add((MWArray)1, (MWArray)1));
}
}
}
And the code, which is a Unity3D script, that failed to use the DLL in Unity3D(some comments have been deleted):
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using RootSystem = System;
using System;
using System.Reflection;
using System.IO;
using Untitled1;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
public class dlltest : MonoBehaviour {
MWArray test1 = 1;
MWArray ref0 = 2;
MWArray result;
ADD myADD;
//Use this for initializations
void Start () {
try
{
myADD = new ADD();
}
catch (Exception e)
{
Debug.Log("EXCEPTION");
Debug.Log(e.ToString());
}
}
// Update is called once per frame
void Update () {
result = myADD.add(test1,ref0);
Debug.Log(result);
}
}
Looks like the static ctor of MWMCR class is calling into an unsupported method in Mono classlib:
(https://github.com/Unity-Technologies/mono/blob/uniy-trunk/mcs/class/corlib/System.Security.Principal/WindowsIdentity.cs#L166)
The reason your test worked as a standalone .Net is that you probably is running it on CLR.
When you try to run your Unity project it uses Mono (in most cases) and then you get this error.
It should work if you build your Unity project as a "Windows Store App" (because in this case your "game" will run using CLR)
I'm developing in C#, and using Dotnetzip's Source code to get the application in one file.
But when running, i get the exception:
System.OverflowException: Arithmetic operation resulted in an overflow.
at Ionic.Crc.CRC32..ctor(Int32 polynomial, Boolean reverseBits) in DotNetZip\CRC32.cs:line 452
at Ionic.Crc.CRC32..ctor(Boolean reverseBits) in DotNetZip\CRC32.cs:line 418
at Ionic.Crc.CRC32..ctor() in DotNetZip\CRC32.cs:line 398
at Ionic.Crc.CrcCalculatorStream..ctor(Boolean leaveOpen, Int64 length, Stream stream, CRC32 crc32) in DotNetZip\CRC32.cs:line 622
at Ionic.Crc.CrcCalculatorStream..ctor(Stream stream) in DotNetZip\CRC32.cs:line 519
at Ionic.Zip.ZipEntry.ExtractOne(Stream output) in DotNetZip\ZipEntry.Extract.cs:line 1043
at Ionic.Zip.ZipEntry.InternalExtract(String baseDir, Stream outstream, String password) in DotNetZip\ZipEntry.Extract.cs:line 870
at Ionic.Zip.ZipEntry.Extract(String baseDirectory, ExtractExistingFileAction extractExistingFile) in DotNetZip\ZipEntry.Extract.cs:line 240
at ItxInstaller.Package.GetData(String instFilePath) in Package.cs:line 32
at ItxInstaller.Install..ctor() in Install.cs:line 26
at ItxInstaller.Program.Main(String[] args) in Program.cs:line 54
The Install.cs is like this:
public Install()
{
// The InitializeComponent() call is required for Windows Forms designer support.
this.InitializeComponent();
Package pack = Package.GetData(Program.args[1]);
this.Title.Text = pack.AppName;
this.PathBox.Text = pack.GeneratePath();
}
The Package.cs contains the GetData():
class Package
{
public string AppName;
public string ExePath;
private string FilePath;
public Package(string filePath)
{
this.ValueInit(filePath);
this.FilePath = filePath;
}
public static Package GetData(string instFilePath)
{
using (ZipFile Package = ZipFile.Read(instFilePath))
{
Package["app.itx"].Extract(Path.GetTempPath(), ExtractExistingFileAction.OverwriteSilently);
}
return new Package(Path.Combine(Path.GetTempPath(), "app.itx"));
}
}
How to solve this exception?
I can reproduce this problem with Mono when using "-checked+" as parameter, i.e. with enabled arithmetic checks. Omitting this parameter results in a working executable.
There is also a project setting for it in Visual Studio.
I've extracted the relevant code into this working program so you can test it yourself:
using System;
namespace Test {
public class Program {
public static void Main(string[] args) {
CRC32 test = new CRC32();
Console.Out.WriteLine(test.dwPolynomial);
}
}
public class CRC32 {
public UInt32 dwPolynomial;
public CRC32() : this(false) {
}
public CRC32(bool reverseBits) :
this(unchecked((int)0xEDB88320), reverseBits) {
}
public CRC32(int polynomial, bool reverseBits) {
this.dwPolynomial = (uint) polynomial; // this is line 452
}
}
}
Using dcms test.cs && mono test.exe runs fine.
Using dcms -checked+ test.cs && mono test.exe results in a
Unhandled Exception: System.OverflowException: Number overflow.
at Test.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.OverflowException: Number overflow.
at Test.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
Update: if you can't or don't want to disable arithmetic checks then you could modify the source code of like 452 to
this.dwPolynomial = unchecked((uint) polynomial);
This turns off arithmetic checks for the expression.