Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for .NET: System.BadImageFormatException when embedding

I'm trying to embed Python in my .NET application.

I'm using Python 3.6.1 64-bit on Windows 10 and I have installed pythonnet 2.3.0 from PyPi using pip.

I've referenced Python.Runtime.dll from C:\Program Files\Python36\Lib\site-packages and have both Path and PYTHONHOME environment variables pointed to C:\Program Files\Python36\.

When I use .NET in Python everything is OK.

import clr
from System.Drawing import Point
p = Point(5, 5)
print(p)

prints {X=5,Y=5} as expected.

But when I call Python from .NET I get System.BadImageFormatException. For example, when calling Python.Runtime.PythonEngine.Initialize(); :

System.BadImageFormatException: 'Could not load file or assembly 'Python.Runtime, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.'

Any thoughts?

Thanks in advance.

like image 884
DfM Avatar asked Jun 07 '17 15:06

DfM


People also ask

How do I resolve System BadImageFormatException?

Solution 1 Usually this is related to the difference in 64bit and 32bit DLL builds and processes. Try compiling to 32bit by changing project properties/Build/Platform Target .

What is System BadImageFormatException?

This exception is thrown when the file format of a dynamic link library (. dll file) or an executable (.exe file) doesn't conform to the format that the common language runtime expects.


1 Answers

As denfromufa said, I was just calling from a 32-bit .NET process.

like image 165
DfM Avatar answered Nov 15 '22 11:11

DfM