C#: using Python.Runtime not found - c#

I tried to embedded a python script using Python for .NET. And in the C# program, I tried to import the class
using Python.RunTime;
but it cannot be found. I cannot find out the reason for that. I have already installed pythonnet in my python interpreter.
I just want to test it out by codes like:
using (Py.GIL)
{
dynamic np = Py.Import("numpy");
MessageBox.Show(np.cos(np.pi * 2));
}
* UPDATE *
I have add reference Python.Runtime.dll in the VS project. And when execute, it got System.BadImageFormatException. I have no clue why that happened.

I hope this answer help others who encountered similar problem.
Add the dll as a reference at the VS. It should be located at locations like "C:\Python27\Lib\site-packages\Python.Runtime.dll." if you have done installation of pythonnet via pip.
System.BadImageFormatException is due to the problem that I set the project to ANY platform, but the python interpreter is 64 bit. Need to change the target platform to match the interpreter.

Related

IronPython.Runtime.Exceptions.ImportException: 'No module named pandas'

I am running C# project which use result of python file. I'm using IronPython to run python file in visual studio. But the error above come up. Please help me. Many thanks!
Sorry you cant access third party functionalities/packages (like Pandas here)
The reason:
Pandas / numpy use great parts of c code, that is a no good for IronPython (.NET).!!!!
If you need to use the power of pandas, i suggest you to create a dialog (send/reveive datas or by file or by calling an external python prog) between your IronPython Project and a program python including pandas.

No module named xlsxwriter.workbook -Ironpython

I was trying to call a python code using C# ironpython. But encountering this error.
"No module named xlsxwriter.workbook"
Getting this error on import line only.
While the same code is running in that machine with regular python(version 2.7)
Please help.
from xlsxwriter.workbook import Workbook
This is happening probably because the xmlwriter library you are referring to is installed in the Python 2.7 interpreter, but not in the IronPython distribution.
You would have to download the xmlwriter package, extract it to a folder and run:
python setup.py install
using the IronPython executable - as shown in https://ironpython-test.readthedocs.io/en/latest/install/index.html.
Hope this helps!

How can I package my python module and its dependencies such as Numpy/Scipy into one file like dll for C# calls?

In my project, some of the algorithms are implemented in python as Modules for calling and libraries such as Numpy/Scipy are used . Now I need to embed these Modules into my UI(implemented by C# and run in Windows 7). There are two reasons I need to package my python modules into a file like DLL(I don't want to package as an .exe because it is not friendly to embed). The first reason is for easily calling, and the second reason is to protect my algorithm source code. Does anyone have any idea?
Finally, I solve my problem by using nuitka. It compile my module into .pyd file, and I can import the module using pythonnet by adding reference Python.Runtime.dll.
My compile command is:nuitka --module --nofreeze-stdlib --recurse-all --recurse-not-to=numpy --recurse-not-to=sklearn --recurse-not-to=pywt --recurse-not-to=matplotlib --recurse-not-to=matplotlib.pyplot --recurse-not-to=scipy.io myfile.py
and my C# code is:
PythonEngine.Initialize();
IntPtr pythonLock = PythonEngine.AcquireLock();
PythonEngine.RunSimpleString("import sys\n");
PythonEngine.RunSimpleString("sys.path.append('C:\\path\\to\\pyd')\n");
PyObject pModule = PythonEngine.ImportModule("modulename");
pModule.InvokeMethod("funcitonname", para1, para2);
Try pythonnet to embed CPython in .NET:
python4.net

"import clr" issue after fine compilation with cx_freeze

I have a problem with import clr that crashes the .exe of my small program.
Here are the imports I use in my program:
import sys
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from PyQt4.QtGui import QApplication, QMainWindow
from PyQt4.Qt import QGridLayout, QWidget
import clr
executablePath = 'E:\\PythonWS\\MyDll\\'
sys.path.append(executablePath)
clr.AddReference("MyDll")
import MyDll
Basically the program compile fine and I get an executable thanks to cx_freeze, but when I launch it with a log, it crashes when comes import clr
I don't know what to do to make it work, if anyone has an idea?
EDIT:
I added a try-except around the import clr like this:
try:
logger.info('in try')
import clr
executablePath = 'E:\\PythonWS\\MyDll\\'
sys.path.append(executablePath)
clr.AddReference("MyDll")
dllPath = clr.FindAssembly('MyDll')
import MyDll
ts = MyDll.TestSystem('127.0.0.1', '127.0.0.1')
print ts.mainBoard.isConnected()
except Exception as e:
logger.info("Unexpected error: {}".format(e))
But even with the try the appplication crashes... That leads me with 2 options,
either my try except isn't good and then why?
there is a real problem with clr and I need help about it.
EDIT2:
I tried importing other module that are from .pyd thinking it might be that the .exe could not find them but all the import I've tried were done without any problem.
EDIT3:
SO! After looking on other posts, I've seen that there were other ways to import dll: by using ctypes for example.
Problem is: my dll is in C# and apparently the import is not supported very well by ctypes... I got errors like WindowsError: [Error -532462766] Windows Error 0xE0434352 which did not help me much since it seems to be a very general error in windows, but this made me think maybe the thing that makes my program crash when importing clr is the same.. Does anyone know what could the error be related to?
So I am back to using .NET clr, but still no luck
For the record: I have tried both python 32 bits and 64 bits. Here are some more information
#with python 32 bits
platform architecture: ('32bit', 'WindowsPE')
sys.platform: win32
os.name: nt
#with python 64 bits
platform architecture: ('64bit', 'WindowsPE')
sys.platform: win32
os.name: nt
So I eventually made it work:
In the end, pythonNET was installed correctly but it seems the version wasn't the best (not sure if not the latest, or not the right version, or bit), so I deleted every file of pythonNET (that I had copy-pasted here and there to be sure it was seen) and downloaded the .whl (here) of a latest version (which wasn't the one pip was downloading).
And eventually the import clr worked...
I hope this helps some of you :)

Not able to run SWIG C# examples in VS 2010

I am trying to get SWIG to work with Visual Studio and C#.
I downloaded swigwin-2.0.4.zip and converted the project to a VS 2010 project.
I am able to build the 'class' example. When I then try to run compiled build I get the error
The type initializer for 'examplePINVOKE' threw an exception.
I haved googled the error, but have not found any suggestions on how to resolve it.
Hope somebody is able to help!
Thanks,
Christian
What worked for me was to:
Go to Build->Configuration Manager. For the C# project change AnyCpu to x86 and rebuild.
Copy example.dll to bin\x86\Debug (Release).
Doesn't require CorFlags.
I got the following answer from Gregory Bronner on the swig-user mailinglist:
I had this issue as well (VS2010 , Windows 7, 64 bit computer, 32 bit mode dll, .NET 4) :
The problem actually relates to being unable to load the DLLs
There were two causes:
#1: All DLLs used by the C# assembly need to be in the same directory (or you need to change the lookup paths).
#2: The C# or the C++ DLL (I forget which) had incorrect CofFlags -- use CorFlags /32Bit+ *.dll or something like that. You could also try using /UpgradeCLRHeader
#3: You need to target the .NET 4.0 system in the project file, but 1 and 2 should get you started.
I will try these hints out and see whether they work and then post an answer if I am able to resolve the issue.
The solution for me was
Move the used dll's to the Release (or Debug) directory
Run CorFlags /32Bit+ file.exe
where file.exe is the executable produced by building the code.
For more information on what is going on Í found the following links helpful
http://www.davesquared.net/2008/12/systembadimageformatexception-on-64-bit.html
http://blogs.msdn.com/b/joshwil/archive/2005/05/06/415191.aspx

Categories

Resources