5

How can I call an IronPython function from within Python? Is there an easy way to interface the two. I need the flexibility of both a full set of proper Python libraries that are not available in IronPython and the latest CLR which Python .net does not currently have.

What I've tried so far is to compile a IronPython dll but I can't get it to be loaded properly within Python.

My attempt to make IronPython n callable from Python

foo.py

def foo():
    print 'hello world'

compile_ipy.py

import clr
clr.CompileModules("foo.dll", "foo.py")

My attempt's to call Iron Python From Python

call_ipy_from_py1.py

import ctypes
dll = ctypes.WindDLL('foo.dll')
dll.foo() # AttributeError: function 'foo' not found

call_ipy_from_py2.py

import ctypes
dll = ctypes.cdll.LoadLibrary('foo.dll')
dll.foo() # AttributeError: function 'foo' not found
2
  • Can you give a simple example? Commented Jan 6, 2015 at 14:21
  • @PeterWood Let's start with calling a function that print's hello world in IronPython from Python, I'll include whati've tried as well. Commented Jan 6, 2015 at 14:35

1 Answer 1

3

.NET DLLs are not the same as C DLLs (which you can use via ctypes). You can, however, use the Python.NET library to call the function like this:

import clr # Imports Python.Runtime.dll
import foo # Imports foo.dll
foo.foo()

I don't know what you mean by "latest CLR which Python .net does not currently have". You can use the version provided here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pythonnet if you need to use CPython 3, I'm using it with .NET 4.5.1 libraries without issues.

Sign up to request clarification or add additional context in comments.

6 Comments

I didn't know about these binaries but I get the following error when I import clr installed this way ImportError: DLL load failed: %1 is not a valid Win32 application.
Also the on the pythonnet source page they list clr 4.0 as the latest, sourceforge.net/projects/pythonnet/files
Regarding the first comment: That normally means that it can't find the DLLs or that you installed the wrong ones (i.e. 64 bit on a 32 bit system). Are Python.Runtime.dll and clr.pyd in your site-packages directory?
Regarding the second one: That page is severly outdated, since the project was kind-of abandoned. Development continued for a while here: github.com/pythonnet/pythonnet and here (for Python 3): github.com/renshawbay/pythonnet
Ah I got this to work correctly now, it was conflicting with another clr.pyd in my Python root directory
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.