I get this error message:
Error 1 No overload for method 'Feval' takes 2 arguments
My matlab function which i call in c# has only one input argument (txt-File)! If i use the command "Feval" it says i need 2 arguments... But which 2arguments? I have only one input parameter... Thank you
The problem:
//matlab.Feval("test_2",input,res); -> Trouble
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// Create the MATLAB instance
MLApp.MLApp matlab = new MLApp.MLApp();
// Change to the directory where the function is located
matlab.Execute(#"cd C:\Users\z003dukj\Documents\MATLAB\test_2");
string[] input = System.IO.File.ReadAllLines(#"C:\Users\z003dukj\Documents\MATLAB\aaaa.txt");
// Define the output
object result = null;
// Call the MATLAB function myfunc
matlab.Feval("test_2",input);
// Display result
object[] res = result as object[];
Console.WriteLine(res[0]);
Console.WriteLine(res[1]);
Console.ReadLine();
}
}
}
The second input to Feval should be the expected number of output arguments of your custom function. In your case, that appears to be zero, so your call to Feval should be
matlab.Feval("test_2", 0, input);
Related
the command
dotnet myapp.dll -- [4, 3, 2] throws the exception System.FormatException: Input string was not in a correct format.
I do not know the syntax. How should I pass arguments correctly?
I use powershell.
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(string.Join('-', args));
}
}
}
Call it via Powershell 6:
dotnet .\ConsoleApp3.dll "[1,2,3]"
Output:
[1,2,3]
In the above call, your Main method will receive [1,2,3] as a single string and you have to parse/split it in your code.
If you want an array reflected in the string[] array of Main you can use a PowerShell array:
dotnet .\ConsoleApp3.dll #(1,2,3)
Output:
1-2-3
Here the PowerShell array #(1,2,3) is casted to a string[]-array. Therefore each item of the PowerShell array is injected to the string[] array.
Behavior is the same on PowerShell 5.1.
I'm trying to call c# static member function from erlang using nfx. I follow doc http://blog.aumcode.com/2013/10/nfx-native-interoperability-of-net-with.html and I am able to call erlang:now from C# and System.DateTime.UtcNow from erlang. However when I try to call non-System from erlang, I get error
** exception error: no match of right hand side value {error,
"unknown type: 'Program'"}
C# code:
namespace erlangIntegration {
public class Program {
static void Main(string[] args) {
var n = new ErlLocalNode("abc", new ErlAtom("'asdf'"));
n.AcceptConnections = false;
n.Start();
var m = n.CreateMbox("test");
var r = m.RPC("r#myPC", "erlang", "now", new ErlList());
Console.WriteLine("Remote time: {0}", r.ValueAsDateTime.ToString());
System.Console.WriteLine("My simple rpc: " + Program.FixedDate());
System.Console.WriteLine("Done. Press any key to exit.");
System.Console.ReadKey();
}
public static DateTime FixedDate() {
return new DateTime(2000, 12, 12);
}
}
}
erlang calls:
(r#myPC)2> f(Time), {ok, Time} = rpc:call('abc#myPC', 'System.DateTime', 'UtcNow', []), calendar:now_to_local_time(Time).
Above call works returning {{2016,1,18},{11,33,17}}
However
(r#myPC)12> f(Time), {ok, Time} = rpc:call('abc#myPC', 'Program', 'FixedDate', []), calendar:now_to_local_time(Time).
returns error:
** exception error: no match of right hand side value {error,
"unknown type: 'Program'"}
I also tried erlangIntegration.Program and to use System namespace.
How to properly make rpc call to c#?
Erlang requires assembly qualified name as input in rpc:call. So instead of 'Program' output of the following code has to be used:
var obj = new Program();
//type from here has to be used in Erlang's call instead of 'Program'
System.Console.WriteLine("Type: " + obj.GetType().AssemblyQualifiedName);
I am currently studying C# and am trying to prepare for next weeks lessons which will be the introduction of classes and methods. To that end i have attempted to build a class called MaxBox which is meant to be a general utility class that I can store some general functions in like 'Displaying a String' or 'Play Again'. I've built my main file (Program) and my class file (MaxBox) and lines #23, #28 and #59 return the same general error 'An object reference is required for the non-static field, method, or property 'program.MaxBox.DisplayStr(string)'. #57 returns a similar error 'An object reference is required for the non-static field, method, or property 'program.MaxBox.PlayAgain()'
I'm a total newb really, and i'm wrestling with objects, I've done some research to get myself this far but I don't understand the language enough yet to be able to understand what the resources I've read are saying I guess to solve this error. Help and guidance is greatly appreciated. I'm still in my first weeks and really I know nothing.
Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; // needed for close
using System.Threading.Tasks;
namespace a020_Breakcase_MeaningOfNames_C
{
class Program
{
public void Play()
{
/*
* Conditionals - Use switch/Case statement too:
* Evaluate user data (name)
* Return meaning of name evaluated
* OR
* Return 'Name not found' error message
* Say goodbye
*/
MaxBox.DisplayStr("What's in a name? Let's find out!");
Console.Write("\n\n");
do
{
MaxBox.DisplayStr("Enter Name: ");
string uName = Console.ReadLine().ToLower();
switch (uName)
{
case "doyle":
Console.WriteLine("Doyle means descendant of Dubhghalle");
break;
case "fiona":
Console.WriteLine("Fiona is considered to be a Latinised form of the Gaelic word fionn, meaning \"white\", \"fair\".");
break;
case "hunter":
Console.WriteLine("Hunter means to search with purpose");
break;
case "liam":
Console.WriteLine("This name is a short form of the Irish name Uilliam (William) which is now use independently as a given name. As a Hebrew name, Liam means \"my people; I have a nation\".");
break;
case "max":
Console.WriteLine("Short for of Maximilian, Maxwell, and the various name using it as a first syllable.");
break;
case "portia":
Console.WriteLine("It is of Latin origin. Feminine form of a Roman clan name. Portia was used by Shakespeare as the name of a clever, determined young heroine in \"The Merchant of Venice\" who disguises herself as a lawyer to save her husband's life.");
break;
default:
Console.WriteLine("I'm sorry but I don't know the meaning of the name " + uName + ".");
break;
}
} while (MaxBox.PlayAgain());
MaxBox.DisplayStr("C#eers!");
}
static void Main(string[] args)
{
Program myProgram = new Program();
myProgram.Play();
Console.Read();
}
}
}
My Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace a020_Breakcase_MeaningOfNames_C
{
class MaxBox
{
/*
* MaxBox is my general functions class
* Contains
* DisplayStr() - Display the string given
* PlayAgain() - If True, runs program again
*/
public String uName;
public String command;
public void DisplayStr(String StrTxt)
{ Console.Write(StrTxt); }
public Boolean PlayAgain()
{
Console.Write("\n\nDo you want to play again? (y)es or (n)o: ");
String command = Console.ReadLine().ToLower().Trim();
if (command == "y" || command == "yes") return true;
return false;
}
}
}
MaxBox's methods are not static, you need an instance of it.
MaxBox maxBox = new MaxBox();
at the beginning of your main class. Then
maxBox.DisplayStr(....)
also, just to get you thinking, you can replace:
if (command == "y" || command == "yes") return true;
return false;
with
return (command == "y" || command == "yes");
The methods PlayAgain and DisplayStr are instance methods on the type MaxBox. In order to call them you need an instance of MaxBox on which to call them. Right now you are trying to call them via the type name which only works for static methods
MaxBox.DisplayStr("hello world"); // wrong
MaxBox mb = new MaxBox();
mb.DisplayStr("hello world"); // right
It is possible to define methods such that you can invoke them from the type name. But doing so requires that they be marked as static
class MaxBox {
public static void DisplayStr2(string str){ ... }
}
MaxBox.DisplayStr2("hello world"); // right
I am trying to figure out how you could go about importing and using a .dll at runtime inside a C# application. Using Assembly.LoadFile() I have managed to get my program to load the dll (this part is definitely working as I am able to get the name of the class with ToString()), however I am unable to use the 'Output' method from inside my console application. I am compiling the .dll then moving it into my console's project. Is there an extra step between CreateInstance and then being able to use the methods?
This is the class in my DLL:
namespace DLL
{
using System;
public class Class1
{
public void Output(string s)
{
Console.WriteLine(s);
}
}
}
and here is the application I want to load the DLL
namespace ConsoleApplication1
{
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(#"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
foreach(Type type in DLL.GetExportedTypes())
{
var c = Activator.CreateInstance(type);
c.Output(#"Hello");
}
Console.ReadLine();
}
}
}
Members must be resolvable at compile time to be called directly from C#. Otherwise you must use reflection or dynamic objects.
Reflection
namespace ConsoleApplication1
{
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(#"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
foreach(Type type in DLL.GetExportedTypes())
{
var c = Activator.CreateInstance(type);
type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] {#"Hello"});
}
Console.ReadLine();
}
}
}
Dynamic (.NET 4.0)
namespace ConsoleApplication1
{
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(#"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
foreach(Type type in DLL.GetExportedTypes())
{
dynamic c = Activator.CreateInstance(type);
c.Output(#"Hello");
}
Console.ReadLine();
}
}
}
Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1 in order to call the method:
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(#"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
var theType = DLL.GetType("DLL.Class1");
var c = Activator.CreateInstance(theType);
var method = theType.GetMethod("Output");
method.Invoke(c, new object[]{#"Hello"});
Console.ReadLine();
}
}
You need to create an instance of the type that expose the Output method:
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(#"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
var class1Type = DLL.GetType("DLL.Class1");
//Now you can use reflection or dynamic to call the method. I will show you the dynamic way
dynamic c = Activator.CreateInstance(class1Type);
c.Output(#"Hello");
Console.ReadLine();
}
Activator.CreateInstance() returns an object, which doesn't have an Output method.
It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.
Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?
If you absolutely want to load the assembly via Assembly.Load, you will have to go via reflection to call any members on c
Something like type.GetMethod("Output").Invoke(c, null); should do it.
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
That loads all the DLLs present in your executable's folder.
In my case I was trying to use Reflection to find all subclasses of a class, even in other DLLs. This worked, but I'm not sure if it's the best way to do it.
EDIT: I timed it, and it only seems to load them the first time.
Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4; i++)
{
stopwatch.Restart();
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
Output:
34
0
0
0
So one could potentially run that code before any Reflection searches just in case.
It's not so difficult.
You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.
Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.
This is pretty simple stuff.
I am creating a program to see if I can run a byte array in C#.
The program should grab a byte array "MyBinaryData" and Load+Run it as a new program.
There will be a text box where you can enter the bytes to see the outcome (it's a experiment ;) ).
I have tried this:
byte[] binaryData = System.IO.File.ReadAllBytes("MyBytes.txt"); // the bytes are in a .txt file for simple tests before becoming a textbox.
Assembly LoadByte = Assembly.Load(binaryData);
MethodInfo M = LoadByte.EntryPoint;
if (M != null)
{ object o = LoadByte.CreateInstance(M.Name);
M.Invoke(o, new Object[] { null }); // this gives the error
}
else {
..... fail code here....
}
The problem is that it gives this error:
"System.Reflection.TargetInvocationException:......SetCompatibleTextRenderingDefault must be called before the first IWin32Window object is created in the application."
My second test was:
Assembly assembly = Assembly.Load(binaryData);
Type bytesExe = assembly.GetType(); // problem: the GetType(); needs to know what class to run.
Object inst = Activator.CreateInstance(bytesExe);
But this needs to know what class in the byte array it needs to run.
I then tried:
var bytes = Assembly.Load(binaryData);
var entryPoint = bytes.EntryPoint;
var commandArgs = new string[0];
var returnValue = entryPoint.Invoke(null, new object[] { commandArgs });
But it gave me this:
"System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: SetCompatibleTextRenderingDefault must be called before the first IWin32Window object is created in the application."
My program.cs is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Crypter
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form2());
}
}
}
What other way can I do this to have the Whole program opened?
Thanks in advance.
You have two way
first way make .exe from that byte array and then start it
second look at this execute byte array