4

Is it possible to compile a library intended for Java with GCJ, get a dll and call from python ctypes?

I'm interested in toxilibs for now, but if anybody knows a toy example that would be great !

Stuart Axon
  • 1,844
  • 1
  • 26
  • 44
  • Can you use Jython? I'm quite sure it would be much, much simpler. – zneak Feb 04 '10 at 22:32
  • 1
    It would, but then it would make using a lot of the C based libraries I can call from CPython a lot harder, and leave me with a dearth of libraries. – Stuart Axon Feb 11 '10 at 00:34

1 Answers1

1

If you want Java-Python hooks, you'd be far better off using Jython and then calling across the boundary that way.

However, yes, it's possible to call an external library from Java; but you don't need GCJ to do that. Rather, you can just bring up a JVM instance inside your Python runtime and then invoke your method(s) for that.

JNI invocation spec

Basically, you want to create your VM at startup, then invoke your method(s) whenever you want:

// Do this once per session, e.g. an __init__ 

JNI_CreateJavaVM(&jvm, &env, &vm_args); 

// When needed invoke Example.foo(int)
jclass cls =
env->FindClass("Example");  jmethodID
mid = env->GetStaticMethodID(cls,
"foo", "(I)V"); 
env->CallStaticVoidMethod(cls, mid,100);

You could write some simple C-wrapper code to invoke this for you from ctypes. However, the JavaVM is a structure of a structure with a number of void* pointers, so might ne non-trivial to do it directly.

AlBlue
  • 23,254
  • 14
  • 71
  • 91
  • I guess I could use a socket between CPython to Jython and call it this way. Really I want to have a mostly CPython program but be able to use some of the processing libraries, for graphics or sound (for instance I'm jealous of their surface library). The way you've posted would certainly work, I just wonder if compiling the lib with GCJ (as in the original question) might not be easier? – Stuart Axon Feb 11 '10 at 00:34