Reputation: 63757
I have a Python C Extension DLL with extension pyd, that I would like to load in Java through System.loadLibrary on windows. It seems that there is no way to load a dll with an extension different from *.dll.
Is there any suggested approach to overcome this issue?
Use Case
I am planning to embed Python in Java. I created an extension dll which I was loading in JAVA, using JNI to communicate with the extension dll which in turn interacts with the Python Runtime Environment to execute the Python Statements
_____ _____ _____
| J | System.loadLibrary | | | P |
| A |-------------------->| P | | Y |
| V | | Y |<-------->| T |
| A | JNI | D | | H |
|___|<------------------->|___| | O |
| N |
|___|
Upvotes: 0
Views: 1195
Reputation: 3908
Have you tried using System.load() instead? You can specify whatever file name you want, but the downside is that you need the complete path to the .pyd file.
It is not hard to search the paths that a .dll would be loaded from:
for (String s: System.getProperty("java.library.path").split(";")) {
String pydName = s + "/mypythonlib.pyd";
File pydFile = new File(pydName);
if (pydFile.exists()) {
System.load(pydName);
break;
}
}
Upvotes: 4
Reputation: 41990
Well, if you just want to run Python code in Java, then Jython will let you compile Python source code into Java .class
bytecode, but you won't be able to use any CPython functionality which uses extension modules.
If you really need to embed CPython in Java, then 'importing' a .pyd
file isn't going to help you. A .pyd
will only function correctly if the Python interpreter has already been initialized will a call to Py_Initialize()
.
What you need to do is look at the CPython embedding docs, and use JNI to call the underlying CPython functions as per the examples in those docs.
Update
It sounds like what you have is a single .dll
file which acts as an extension module, but also exposes some symbols you're using to embed Python in Java. If you never plan to import it in CPython, then just rename it to .dll
.
If you do need to import it in CPython, then you probably ought to split the functionality into two separate .dll
files - one which you use in the JNI embedding, and the other which just acts as an extension module.
Upvotes: 1
Reputation: 10727
See Calling Python in Java?. Basically, you use either org.python.util.PythonInterpreter
to call Python or Jython. Another possible solution is to use a UNIX-style .so file. Yet another choice may be to use get the current path, merge it with the name of the .pyd file, and use System.load() as specified by Markku K.
Upvotes: 1