Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I want to run python script from C#(Visual Studio). I don't want to use C# process to do it, because I must have access to all of the python's modules, classes, and methods (I'd like to treat it as python object). I'm looking for sth like this:
"Python code"
"PyModule"
class PyClass:
def method:
print("Hello world!")
C# code
using PyModule.PyClass
PyClass.method()
I found python.net http://pythonnet.github.io/ , but they say that their solution is unverifiable.
I have to write it in Python 3, so IronPython isn't solution for me.
Do you know any solution that is similar to this?
Well, do have a look into IronPython as suggested in the comments. You can write your python script, save it to, say, greet.py
def greet(name):
return 'Hello ' + name + '!'
Now from C# you can do:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
static void RunPythonScript()
{
var engine = Python.CreateEngine();
dynamic scope = engine.CreateScope();
engine.ExecuteFile("greeting.py", scope);
var greeting = scope.greet("John");
Console.WriteLine(greeting);
}
Result as you might expect is Hello John!
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Is there an attribute or capability in C# to automatically memoize static function results, based on input parameters, without writing all the logic for it myself?
For example in Python you can depend on functools:
import functools
#functools.lru_cache()
def my_function(param1):
...
Is there some similar package or built-in for C#?
[Memoizable]
public static MyFunction(MyType param1)
{
...
Results should be cached to avoid re-calculating for the same inputs.
Nope, does not exist. There are external tools that do so, but there is nothing automatic in C# for this. You will have to program it, if you need it, or use some external tool that does code rewrite.
public class SampleClass
{
private readonly IDictionary<int,int> _cache =
new Dictionary<int, int>();
public int Calculate(int input)
{
if (!_cache.ContainsKey(input))
{
int result = input*2;
_cache.Add(input,result);
}
return _cache[input];
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
From a C# program, I want to examine a given python file for the functions it offers. If possible, I also want to get metainformation about each function and parameter, like a description.
I can control both the C# side and the Python side.
How can I achieve that?
(As for the use case: I am going to write a dispatcher function in Python that the C# program can call inside the python script to execute a specific function, given the required arguments.)
Never tried this. But think you could use a combination of the module optparse (Taken from How do I get list of methods in a Python class?):
from optparse import OptionParser
import inspect
inspect.getmembers(OptionParser, predicate=inspect.ismethod)
With function.__doc__ to get the documentation from the method like
def factorial(x):
'''int f(int x); returns the factorial of an integer number'''
#code here
>>> factorial.__doc__
'int f(int x); returns the factorial of an integer number'
Use the first part (int f(int x);) as the description of what parameters it needs and returns (You could take this part just taking the string until first semicolon)
And use getattr to call the function (https://docs.python.org/2/library/functions.html#getattr):
getattr(myObject, 'factorial', '3')()
Hope this helps you
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm not even sure how should I frame this question so that you all get what actually I'm asking for.
I'm wondering how does the keywords work in programming languages, being specific, C#. In the below code:
using System;
namespace TestApplication
{
class Program
{
static void Main(string[] args)
{
string s = "Hello";
Console.WriteLine(a.ToString());
Console.ReadLine();
}
}
}
Here, Console is a predefined class of System namespace which lies in mscorlib.dll. So when the compiler/CLR meets the Console.WriteLine(), it will invoke the static method WriteLine() with appropriate overload.
So the definition of WriteLine method and Console class all are already written and kept in the System namespace of the mscorlib assembly.
But my question is when the complier/CLR meets with the keywords like using,namespace, class,static, what does it do? Where is it written that it must treat the word next to the class keyword as a new type? Is it built in to the compiler/CLR? How does it work then?
C# keywords, which you can see the full list of here, are built into the CSC compller. When the compiler comes across any keyword, it is programmed to know what to expect and what to do.
This is part of the compiler, not the BCL. Check out the language specification which explains exactly what the compiler must do when it encounters any of the keywords.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Basically I have two questions:
1) How to emit or generate a IronPython code (tools, libs) in a C# application. The result of this process should be string consisting of real IronPython code not IL code.
2) How beneficial is the approach above over generating a IronPython code on your own (simply by using StringBuilder)?
I am looking for some code generator library similar to this IMAGINARY pseudo code generator:
IronPythonCodeGenerator generator = new IronPythonCodeGenerator();
Parameter param = new Parameter("str");
ParameterValue value=new ParameterValue(param,"This piece is printed by the generated code!!!");
Function function = IronPythonCodeGenerator.CreateFunction("PrintExtended",param);
function.AppendStatement("print",param);
function.AppendStatement(Statements.Return);
FunctionCall functionCall = new FunctionCall(function,value);
generator.MainBody.Append(function);
generator.MainBody.Append(functionCall);
Console.WriteLine(generator.MainBody.ToString());
, which outputs the IronPython code:
def PrintExtended( str ):
print str;
return;
PrintExtended("This piece is printed by the generated code!!!");
Reflection.Emit is for generating IL code, not for generating high-level language code. So if your target language is IronPython, building it up in a StringBuilder is probably your best bet.
It of course depends on your needs. If all you want to do is just generate code without wanting to change the order of methods, or modify methods after they've been defined etc., just constructing code in a StringBuilder and then compiling it would be the easiest way.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm working on a project that combines a very large open source project (OSP) written in C and attempting to build a front end in C#. I'm currently compiling the OSP with Visual Studio 2012 Express and generating all the .exe's, .dll's,etc from this project.
How should I perform the integration? (Remember I have full access to the .h/.c files) I attempted using the IJW (It Just Works) method, but it didn't appear to allow me to import the references for my freshly compiled .dll's. Apart from that, I'm not sure how to execute the various functions within C# (apart from sending command line commands to the .exe's, which I would prefer not to do....)
Do I need to compile the OSP with special options/parameters for IJW, or would it require code rewrite?
For DLL written in C, you need to write the equivalent declarations in C# instead of adding reference to that DLL.
This is called PInvoke.
class ABC
{
[DllImport("abc.dll")]
public static extern int FuncX(int x, int y);
}