I'm trying to import a VERY SIMPLE custom C# class into Python using pythonnet. I've never used C# or VS, so It's probably some stupid mistake I'm doing.
I have got a solid C# code base (not written by me) that I want to drive using Python.
I have this C# class:
using System;
public class MyClass
{
string text;
public MyClass(string text)
{
this.text = text;
}
public void Write()
{
Console.WriteLine(text);
}
}
In VS 2017, I've created a .NET Core Class Library project. It compiles fine and creates a MyClass.dll file.
Then I'm trying to import it in Python:
import sys
sys.path.append(r"C:\Users\myuser\source\repos\hello\MyClass\bin\Debug\netcoreapp2.1")
import clr
clr.FindAssembly(r"MyClass")
clr.AddReference('MyClass')
import MyClass
But I always get a "ModuleNotFoundError: No module named 'MyClass'" error.
Turns out I was compiling the DLL with .NET Core. Changing to .NET Framekwork 4.5 solved the problem.
I wish the error messages were more helpful.
Related
with absolutely no knowledge of coding in C#, I wish to call a C# function within my python code. I know there's quite a lot of Q&As around the same problem, but for some strange reason, i'm unable to import a simple c# class library from a sample python module.
Here's below as to what i've done -
C# Class Library setup
I'm using the VS 2017 CE.
I create a new project TestClassLibrary under the type of ClassLibrary(.NET Standard)
The classes inside the project are as follows -
MyClass.cs
using System;
namespace TestClassLibrary
{
public class MyClass
{
public string function()
{
return "Hello World!";
}
}
}
This was built successfully, generating the .dll file under the \bin\Debug\netstandard2.0 dir as TestClassLibrary.dll
Now, I switch over to python3.6 (running on a virtualenv, backed with pythonnet 2.3.0)
main.py
import sys
sys.path.append(r"<Ablsloute Path to \bin>\Debug\netstandard2.0")
import clr
clr.AddReference(r"TestClassLibrary")
from TestClassLibrary import MyClass
When i Run python main.py, the code fails with the error -
Traceback (most recent call last):
File "main.py", line 6, in <module>
from TestClassLibrary import MyClass
ModuleNotFoundError: No module named 'TestClassLibrary'
Should the code be -
import sys
sys.path.append(r"C:\Users\DELL\source\repos\TestClassLibrary\TestClassLibrary\bin\Debug\netstandard2.0")
import clr
clr.AddReference("TestClassLibrary.dll")
from TestClassLibrary import MyClass
I get -
clr.AddReference("TestClassLibrary.dll")
System.IO.FileNotFoundException: Unable to find assembly 'TestClassLibrary.dll'.
at Python.Runtime.CLRModule.AddReference(String name)
But when i ran the code below, the code runs as expected -
import clr
clr.AddReference(r"System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello World!")
I've no idea of what i might be missing :(
This is really janky but how I like to do things that are personal projects.
Python lets you send stuff to the command line really easily. C# can be run from command line. You probably see where I'm going with this.
Try adding C sharp to PATH. import os to python. then use this line of code when you want to run the C# script:
os.system("csc nameofscript.cs")
perhaps I've misunderstood, but this is how I would make it work on my machine
i am just starting to develop in monodroid , i know android and c# too. i have created android app using viewflow example. so i have now viewflow library 's jar file , i have included that .jar file in my monodroid java binding library as defined in http://docs.xamarin.com/Android/Guides/Advanced_Topics/Java_Integration_Overview/Binding_a_Java_Library_(.jar). But when i build that java library project i have got following error.. i have stuck with this almost 3 hrs.
'Org.Taptwo.Android.Widget.ViewFlow' does not implement inherited abstract member 'Android.Widget.AdapterView.RawAdapter.set'
This has been filed as bug 11279. The workaround is to add a file to your binding project with the following contents:
using Android.Runtime;
namespace Org.Taptwo.Android.Widget {
partial class ViewFlow {
protected override Java.Lang.Object RawAdapter {
get {return Adapter.JavaCast<Java.Lang.Object>();}
set {Adapter = value.JavaCast<global::Android.Widget.IListAdapter>();}
}
}
}
Change the namespace and type name as appropriate to fix other binding projects.
I getting bug: crash happened outside the Java Virtual Machine in native code. whenever i run with class file with native library and .net module file it works fine.
but when i try to run alone class file and native library it gets crash .please clarify my mistake i have done, please review my code.
for your reference with parameter
==========================================
public class Sum
{
public int add(int a, int b)
{
return a + b;
}
}
===========================================
save as Sum.cs and compile it to module
using cmd:
csc /t:module sum.cs
Create Java File to test
===========================================
public class test{
public native int add(int a,int b);
static {
System.loadLibrary("JSample");
}
public static void main (String[] args) {
System.out.println(new test().add(10,15));
}
}
==========================================
save it as test.java compile as
javac test.java
create native header file
javah -jni test
it will create test.h
create win32 project using visual studio (I used VS2010)
Choose project name as JSample
include header and C#.net module
write header for manged C++ conversion
==============================================
#using <mscorlib.dll>
#using "Sum.netmodule"
using namespace System;
public __gc class SumC
{
public:
Sum __gc *t;
SumC()
{
t = new Sum();
}
int callCSharpSum(int a,int b)
{
return t->add(a,b);
}
};
===========================================
save it as sum.h
create sum.cpp file
============================================
#include <jni.h>
#include "test.h"
#include "sum.h"
JNIEXPORT jint JNICALL Java_test_add
(JNIEnv *, jobject, jint a, jint b)
{
SumC* t = new SumC();
return t->callCSharpSum(a ,b );
}
=============================================
optimize compiler to build /clr:oldSyntax
Include Jdk/Include directory path
build the project.
we will Get JSample DLL
run the project
with C#.net module,Native DLL file and class file at the same folder.
java test
25
but whenever i run the code with dll file and class file alone.
it shows bug report The crash happened outside the Java Virtual Machine in native code.
please clarify how to port managed code C# into C++ (Win32 Un-Managed code). library file.
To use .NET assemblies from Java, I strongly suggest you look at IKVM, which is a Java VM that bridges to .NET Runtime.
I've used this back in (I think) 2004 for production software and it worked nicely. The project is actively maintained and recieves support for .NET 4 and Java 7 these days.
You have a choice of
running the Java code in IKVM so you can use .NET libraries
run a .NET program that loads java libraries (e.g. jars)
Both ways, there is a preprocessing step to translate the jars to DLLS or viceversa.
See http://ikvm.net
I created a C# class library using visual studio and it works well in visual studio, and when trying to execute it in mono develop I get error the library code:
namespace ClassLibrary2
{
public class Class2
{
public static void dosomething() {Console.WriteLine("dfss"); }
}
}
the code in mono develop:
namespace cons
{
class MainClass
{
public static void Main (string[] args)
{
ClassLibrary2.Class2.dosomething();
}
}
}
the error
What target framework (2.0, 3.5, 4.0) did you specify in VS?? It seems that your mono develop uses different (lower) version.
You need to check that your .Net Framework versions are the same. You will have chosen a framework in VS that is different to that which mono develop is trying to use. This is a very common cause of this error.
The missing assembly is ClassLibrary2 and your code only deals with ClassLibrary1.
Maybe you could add the registry key to enable a more verbose logging.
i have created a C# dll file on my machine as shown below:
namespace myDLL
{
public class myClass
{
public string myFunction()
{
return "I am Here";
}
}
}
then i created a tlb file with "tlbexp" command,
then i used the "regasm" command n registered this dll on my machine.
When i created an object of type myClass on my machine using VBScript, everything is working fine... here i used the CreateObject() method as shown below:
Set myObj = CreateObject("myDll.myClass")
Now i want to create an object of type myClass from VBScript that is running on another machine, how can i do this. please help me how can i access that dll file, am using the CreateObject() function as shown below:
Set HD = CreateObject("myDll.myClass","myMachineName")
now am getting error as "permission denied".
It appears that this is supported if the assembly is built with as COM visibility enabled.
Is it possible to execute a .NET assembly(dll) from vbscript?
By the way, I was pretty delighted to find out that there is a JScript compiler for .NET which allows one to write .NET code using JScript and also to target other .NET assemblies but unfortunately I haven't found anything similar for VBScript.