I have a C# class library that contains some specialized mathematical functionality relating to raster processing (it uses some asynchronous techniques to spped up the processing). I have a project that my client wants written using Ruby on Rails (RoR) on a Linux box, that can benefit from using this library (I'd rather not port it to Ruby or C++).
The first part of my question is:
Can a standalone Mono-based DLL be created from my C# DLL? (By standalone I mean, the DLL can be utilized WITHOUT having mono installed (all required libraries would be included in the single DLL)?
And the second part, if the answer to part 1 is 'yes', can this standalone mono-based DLL be called from Ruby?
EDIT 11/22/2014
I have made a little progress possibly. I have created a *.so file by using
mono --aot -O=all dlltest.dll
(Obviously I now have Mono installed on my Ubuntu test VM.) This results in dlltest.so, which I then add a symbolic link for in /usr/lib.
The code for my test Ruby script is:
require 'ffi'
module CsharpTest
extend FFI::Library
ffi_lib 'dlltest.so'
attach_function :Hello, [], :string
end
ret_str = CsharpTest.Hello()
puts ret_str
Note that my simple C# class is:
using Systems;
namespace DllTest
{
public static class MyClass
{
public static string Hello()
{
return "Hello World";
}
}
}
When I run the test Ruby script (ruby test.rb) I get the following error:
....:in 'attach_function': Function 'Hello' not found in [dlltest.so] (FFI::NotFoundError)
Using 'nm -Ca dlltest.so' the available functions are listed. One of them is '0000000000001010 t DllTest_MyClass_Hello'. If I use this label as opposed to 'Hello' I get a similar error.
Also note that 'nm -D --defined-only dlltest.so' does not list any functions with 'Hello' in them.
I'm still not sure if I've on the right track, but is there anything more I can try? Or is this approach a dead end?
I have designed the code in MATLAB and it's working fine. I was working in GUI in MATLAB but it's a headache for me. I think i can create GUI simply and effectively. Can we create GUI in C# that will also run the whole code of MATLAB that i have designed??
Yes, this is possible. For details, take a look at:
Calling a MATLAB function from C#
Integrating MATLAB with C#
MATLAB Compiler
If you need a quick and dirty way to wrap MATLAB code with a C# GUI (e.g. WinForms), one option is to create an exe from your MATLAB code (.m) - from .NET, you can then easily start this exe as a new process. Note that this approach may not be the best in some situations, beacuse the delay introduced with an exe call can be quite substantial (as the other answer explains).
An example: first, write MATLAB code as a function:
function y=SamplePlot(p, d, w, t)
numericValueP=str2num(p);
numericValueD=str2num(d);
numericValueW=str2num(w);
time=str2num(t);
%... do stuff ...
plot(...);
Input parameters will be passed to this code as string parameters via command line, hence they are converted via str2num. E.g. a MATLAB call
SamplePlot('1', '2', '3', '4')
will be represented as
SamplePlot.exe 1 2 3 4
Now, create a standalone console app from .m file: in MATLAB console, write:
deploytool
Name: SamplePlot.prj (for example). Target: Console application.
Add .m file.
Package: add MCR (this is MATLAB Compiler Runtime - this is what an end-user will need if he doesn't have MATLAB installed; for local testing, you don't need to add this).
Then use:
mbuild -setup
Finally, click 'build' icon. After some time, an exe is generated. Now, you can start this exe as a process from a C# application, e.g. on button click:
private void button1_Click(object sender, EventArgs e)
{
string p=TextBox1.Text;
string d=TextBox2.Text;
string w=TextBox3.Text;
string t=TextBox4.Text;
string params = String.Format("{0} {1} {2} {3}",p,d,w,t);
System.Diagnostics.Process.Start("SamplePlot.exe", params);
}
I left out some minor details, but this is one possible option.
(If I recall correctly, an assembly can be generated this way as well; you can then call the assembly instead of an exe file).
I'm pretty unfamiliar with C# but eventually happened to use .NET classes from MATLAB.
So, you could also do it the other way round, than the previous answers suggest:
Since MATLAB is able to create/open .NET gui-elements like dialog, I guess you should also be able to open your .NET-GUI from MATLAB an then plug in your MATLAB-Code via Callbacks.
See e.g.:
http://www.mathworks.de/de/help/matlab/matlab_external/getting-started-with-net.html
Depending on how frequently you want to execute matlab-code from your gui and how long the matlab-processing time usually is, this also avoids the pretty large overhead that's e.g. introduced by using a .exe generated with the MATLAB compiler.
Say, you'd like to do quick matrix-calculation operations taking less than a second with every other button-click, than starting a standalone.exe everytime would make your gui pretty useless.
This link is so useful and simple:
Call MATLAB Function from C# Client
I have the problem loading the DLL file and calling the functions in Python.
I have tried a lot of tutorials, but still can't figure out how it works.
This is my class to export as DLL file. I use simple C# code.
namespace DemoClassLib
{
public class cLib
{
public int increment(int x)
{
return x + 1;
}
}
}
After building the C# code, I get the DLL file called "DemoClassLib.dll".
I use ctypes to load the DLL file. Everything is okay until now.
from ctypes import *
myDll = WinDLL('D:\\Resources\\DemoClassLib\\bin\\Debug\\DemoClassLib.dll')
Starting from that point, I can't continue.
All the commands I have tried are failed.
n = c_int(1)
myDll.increment(n)
It keeps on showing me the errors.
How can I call the method "increment()" in Python?
And how can I pass the input and retrieve the output from that?
I am very new to Python.
Can someone help me please?
I would be very appreciated if you can provide me the source code tutorial.
You can't do this with ctypes because there is no symbol in the binary called simply "increment", as your increment method is a member of a class. Even if this were C++ the name would be mangled. But with C# you don't even get a mangled name in the symbol table because the code is interpreted by the .NET framework.
If you must for some reason interface with a C# library you may want to consider trying IronPython (http://ironpython.net/) which is Python running on the .NET framework with full access to the CLR. The comment above suggesting exposing a COM interface could also work.
How can I read from standard input and write to standard output. System.Diagnostics.Process.StandardInput's MSDN reference didn't help as it separately starts the process and then redirects the Standard Input/Output but what If the process is already running and called my Application to feed it some data. Here's an example to make things a bit clear:
I am simply using Unix pipes i.e. cat command in cygwin (A Linux like Environment for windows) that basically just reads standard input and print to standard output. following is the command:
% cat input/sample.txt | src/csharp/maptest
But that doesn't seems to work.
If some one know ruby here as i don't here's what i want to do the same in C#:
#!/usr/bin/env ruby
STDIN.each_line
do |line|
some code here
end
And here's some python equivalent code that i want to accomplish in c# or vb.net:
#!/usr/bin/env python
import re
import sys
for line in sys.stdin:
val = line.strip()
Any solutions?
Thanks in advance.
You're looking for the static methods in the Console class :
System.Console.In encapsulate the standard input stream
System.Console.Out encapsulate the standard output stream
Pointers to documentation for System.IO.Pipes are a red herring here.
If you just want the ability to have a process pipe its standard output to another process's standard input, then this works the same as you would expect provided the target process is written to read input from standard input. For example I can do
dir /b /s c:\*.* | findstr exe
to find all executable files on my C: drive.
All you need to do therefore is to build your maptest application so that it reads from standard input, in other words it must accept input via the Console.Read* methods as mentioned in other answers. See this previous question for an earlier discussion
C# Console receive input with pipe
You can't use Console.ReadLine() and Console.WriteLine()?
Never mind the above. Have you tried System.IO.Pipes? Here's the MSDN documentation.
I wonder if there is something like a standalone Version of Visual Studios "Immediate Window"? Sometimes I just want to test some simple stuff, like "DateTime.Parse("blah")" to see if that works. But everytime i have to create a new console application, put in my code and test it.
The Immediate Window sadly only works when I am debugging something. Could PowerShell do that? Just open a CLI similar to what cmd.exe does, allowing me to execute some C# code?
Linqpad - I use it like this all the time. http://www.linqpad.net/
Don't be misled by the name - that just describes the original motivation for it, not its functionality.
Just recently he released a version with proper statement completion - that's a chargeable add-on (the core tool is free), but a minute amount of money and well worth it, I think.
The Mono project includes an interactive C# shell, this may be just what you're looking for.
http://www.mono-project.com/CsharpRepl
C# Interactive window and csi.exe REPL were added to Visual Studio 2015 Update 1:
Introducing Interactive
The Interactive Window is back! The C# Interactive Window returns in Visual Studio 2015 Update 1 along with a couple other interactive treats:
C# Interactive. The C# Interactive window is essentially a read-eval-print-loop (REPL) that allows you to play and explore with .NET technologies while taking advantage of editor features like IntelliSense, syntax-coloring, etc. Learn more about how to use C# Interactive on Channel 9 or by reading our beginner’s walkthrough.
csi. If you don’t want to open Visual Studio to play around with C# or run a script file, you can access the interactive engine from the Developer Command Prompt. Type csi /path/myScript.csx to execute a script file or type simply csi to drop inside the command-line REPL.
Scripting APIs. The Scripting APIs give you the ability to execute snippets of C# code in a host-created execution environment. You can learn more about how to create your own C# script engine by checking out our code samples.
See What’s New in Visual Studio Update 1 for .NET Managed Languages.
Basically, now you have:
IDE REPL — C# Interactive window in VS
Script interpreter — csi foo.csx from Dev Cmd Prompt
Command line REPL — csi from Dev Cmd Prompt
Scripting API
Try scriptcs, it's not integrated into the VS IDE but it does let you type and run C# in a script window without the need for a project compiler etc...
Well, this isn't a direct answer to your question, but you could look at this tool:
Snippet Compiler
Also, if you want to see the IL produced, or similar, there is a tool that plugs into Reflector, called Snippy, based on the Snippy tool that Jon mentions in his own answer further down.
All of these are very nice to use.
As you suggest, PowerShell can do what you want. For example, to test your DateTime.Parse, the following one liner will do the trick:
PS C:\Documents and Settings\Dan> [System.DateTime]::Parse("Blah")
Exception calling "Parse" with "1" argument(s): "The string was not recognized as a valid DateTime. There is a unknown
word starting at index 0."
At line:1 char:25
+ [System.DateTime]::Parse( <<<< "Blah")
PS C:\Documents and Settings\Dan> [System.DateTime]::Parse("1/2/3")
01 February 2003 00:00:00
Note that the above uses the current release of PowerShell (v1.0). The next version of PowerShell will allows you to intermingle C# with PowerShell scripts more directly. To whet your appetite, watch this 7 minute screencast "C# to PowerShell" by Doug Finke. Very impressive!
If you're using Mono, there's this:
CsharpRepl
Don Box hacked something very simple up a few years ago too.
Along the lines of lassevk's answer, I've got "Snippy". This was developed for C# in Depth, and the UI is pretty rubbish, but it works - and lets you write extra members (methods, nested classes etc) as well, e.g.
public static void Foo()
{
Console.WriteLine("Hello");
}
...
Foo();
(The ... is used to tell Snippy "everything under here belongs in Main".)
We've just released CShell a full featured C# REPL IDE. It supports code completion, script files, adding references and is really extensible. Also we plan to add NuGet support soon, which will make it super quick to write some code and see how it works.
http://cshell.net/
We love LINQPad but it doesn't have a REPL, the code is executed once and you cannot do anything further with the results unless you modify the script and run the whole script again. This is okey, but sometimes if you want even more a scripty feeling then to evalute your code in a REPL is really nice and convenient.
I also find that SharpDevelop is so quick and lightweight that it is the easiest way to whip off a quick test project.
You may find the Object Test Bench useful. It's not very well known, but lets you create instances of classes, execute static methods and so on. It can be useful for discovering how to use unfamiliar APIs or for quick debugging of your own classes and methods, saving the creation of a test harness for simple checks.
You can find the MSDN documentation here:
http://msdn.microsoft.com/en-us/library/c3775d98%28VS.80%29.aspx
If you could wait a while.. it looks like there could be a C# equivalent of Ruby's irb in time for C# 4.0
Anders H. demonstrated an interactive console session where you could type in arbitrary C# code and see results in his 'Future of C#' piece at PDC 2008. You could even pop a WPF Window from it and then play with it via the console interface. Pretty cool.
Use LINQPad.
Name notwithstanding, it can execute any C# or VB code, from simple expressions to entire classes.
Plus, it can visualize entire object graphs in the results.
You can even add references to your own assemblies.
Try the C# REPL Script Environment that is part of the O2 Platform. It is exactly what you are asking for.
It will give you a perfect environment to try out all C# features and APIs (conceptually the O2 REPL environment is similar to LinqPAD)
You should also take a look at Roslyn from Microsoft. On Multiple Roslyn based tools (all running Stand-Alone outside VisualStudio) , the first one is a simple Roslyn REPL
If you happen to know and like Python, then IronPython may be a good alternative. It comes with a (Python) REPL console (ipy.exe) where you can import and use all of the .Net types.
I find it useful for testing out little things, exactly like DateTime.Parse("Blah").
Note that it can't actually execute C# code, but if all you want is access to .Net, then it's perfect. Also, if you install the IronPython Tools for VS, you can start a REPL session right in VS using a single keyboard shortcut (Alt+I) and leave it running in a docked window for when you need it.
Update: http://avillenas.com/post/interactive-c
Well, you can try this.
Download and install dotnet.github.io
Open cmd
Type "dotnet repl"
Type whatever you need.
I did what you wanted to do. Click here to see the gif
The Roslyn project sources contain a REPL called CSI (http://sourceroslyn.io/#csi/Csi.cs). The Csi class is currently internal but with the the “csi” project (Roslyn.sln: Interactive/Hosts/csi) an executable console application is available that supports e. g. the command #r to load an assembly and #load to load and execute script files (start the csi and use #help).