Giter VIP home page Giter VIP logo

pyjnius's Introduction

PyJNIus

PyJNIus is a Python library for accessing Java classes using the Java Native Interface (JNI).

PyJNIus is managed by the Kivy Team and can be used with python-for-android.

It can also be used independently of Kivy, on desktop and mobile platforms.

Warning

The PyPI package name is now pyjnius instead of jnius.

Backers on Open Collective Sponsors on Open Collective GitHub contributors Contributor Covenant

PyPI - Version PyPI - Python Version

Tests Tests (x86) Builds

Installation

pip install pyjnius

Quick overview

    >>> from jnius import autoclass
    >>> autoclass('java.lang.System').out.println('Hello world')
    Hello world
    
    >>> Stack = autoclass('java.util.Stack')
    >>> stack = Stack()
    >>> stack.push('hello')
    >>> stack.push('world')
    >>> print(stack.pop())
    world
    >>> print(stack.pop())
    hello

Usage with python-for-android

  • Get python-for-android
  • Compile a distribution with kivy (PyJNIus will be automatically added)

Then, you can do this kind of thing:

from time import sleep
from jnius import autoclass

Hardware = autoclass('org.renpy.android.Hardware')
print('DPI is', Hardware.getDPI())

Hardware.accelerometerEnable(True)
for x in range(20):
    print(Hardware.accelerometerReading())
    sleep(0.1)

It will output something like:

I/python  ( 5983): Android kivy bootstrap done. __name__ is __main__
I/python  ( 5983): Run user program, change dir and execute main.py
I/python  ( 5983): DPI is 160
I/python  ( 5983): [0.0, 0.0, 0.0]
I/python  ( 5983): [-0.0095768067985773087, 9.3852710723876953, 2.2218191623687744]
I/python  ( 5983): [-0.0095768067985773087, 9.3948478698730469, 2.2218191623687744]
I/python  ( 5983): [-0.0095768067985773087, 9.3948478698730469, 2.2026655673980713]
I/python  ( 5983): [-0.028730420395731926, 9.4044246673583984, 2.2122423648834229]
I/python  ( 5983): [-0.019153613597154617, 9.3852710723876953, 2.2026655673980713]
I/python  ( 5983): [-0.028730420395731926, 9.3852710723876953, 2.2122423648834229]
I/python  ( 5983): [-0.0095768067985773087, 9.3852710723876953, 2.1835119724273682]
I/python  ( 5983): [-0.0095768067985773087, 9.3756942749023438, 2.1835119724273682]
I/python  ( 5983): [0.019153613597154617, 9.3948478698730469, 2.2122423648834229]
I/python  ( 5983): [0.038307227194309235, 9.3852710723876953, 2.2218191623687744]
I/python  ( 5983): [-0.028730420395731926, 9.3948478698730469, 2.2026655673980713]
I/python  ( 5983): [-0.028730420395731926, 9.3852710723876953, 2.2122423648834229]
I/python  ( 5983): [-0.038307227194309235, 9.3756942749023438, 2.2026655673980713]
I/python  ( 5983): [0.3926490843296051, 9.3086557388305664, 1.3311761617660522]
I/python  ( 5983): [-0.10534487664699554, 9.4331550598144531, 2.1068975925445557]
I/python  ( 5983): [0.26815059781074524, 9.3469638824462891, 2.3463177680969238]
I/python  ( 5983): [-0.1149216815829277, 9.3852710723876953, 2.31758713722229]
I/python  ( 5983): [-0.038307227194309235, 9.41400146484375, 1.8674772977828979]
I/python  ( 5983): [0.13407529890537262, 9.4235782623291016, 2.2026655673980713]

Advanced example

When you use autoclass, it will discover all the methods and fields of the class and resolve them. You may want to declare and use only what you need. The previous example can be done manually as follows:

from time import sleep
from jnius import MetaJavaClass, JavaClass, JavaMethod, JavaStaticMethod

class Hardware(JavaClass):
    __metaclass__ = MetaJavaClass
    __javaclass__ = 'org/renpy/android/Hardware'
    vibrate = JavaStaticMethod('(D)V')
    accelerometerEnable = JavaStaticMethod('(Z)V')
    accelerometerReading = JavaStaticMethod('()[F')
    getDPI = JavaStaticMethod('()I')

# use that new class!
print('DPI is', Hardware.getDPI())

Hardware.accelerometerEnable()
for x in range(20):
    print(Hardware.accelerometerReading())
    sleep(0.1)

You can use the signatures method of JavaMethod and JavaMultipleMethod, to inspect the discovered signatures of a method of an object

>>> String = autoclass('java.lang.String')
>>> dir(String)
['CASE_INSENSITIVE_ORDER', '__class__', '_JavaClass__cls_storage', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__javaclass__', '__javaconstructor__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__pyx_vtable__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'charAt', 'checkBounds', 'clone', 'codePointAt', 'codePointBefore', 'codePointCount', 'compareTo', 'compareToIgnoreCase', 'concat', 'contains', 'contentEquals', 'copyValueOf', 'empty', 'endsWith', 'equals', 'equalsIgnoreCase', 'finalize', 'format', 'getBytes', 'getChars', 'getClass', 'hashCode', 'indexOf', 'indexOfSupplementary', 'intern', 'isEmpty', 'join', 'lastIndexOf', 'lastIndexOfSupplementary', 'length', 'matches', 'nonSyncContentEquals', 'notify', 'notifyAll', 'offsetByCodePoints', 'regionMatches', 'registerNatives', 'replace', 'replaceAll', 'replaceFirst', 'split', 'startsWith', 'subSequence', 'substring', 'toCharArray', 'toLowerCase', 'toString', 'toUpperCase', 'trim', 'valueOf', 'wait']
>>> String.format.signatures()
[(['java/util/Locale', 'java/lang/String', 'java/lang/Object...'], 'java/lang/String'), (['java/lang/String', 'java/lang/Object...'], 'java/lang/String')]

Each pair contains the list of accepted arguments types, and the returned type.

Troubleshooting

Make sure a Java Development Kit (JDK) is installed on your operating system if you want to use PyJNIus on desktop. OpenJDK is known to work, and the Oracle Java JDK should work as well.

On Windows, make sure JAVA_HOME points to your Java installation, so PyJNIus can locate the jvm.dll file allowing it to start Java. This shouldn't be necessary on macOS and Linux, but in case PyJNIus fails to find it, setting JAVA_HOME should help.

License

PyJNIus is MIT licensed, actively developed by a great community and is supported by many projects managed by the Kivy Organization.

Documentation

Documentation for this repository.

Support

Are you having trouble using PyJNIus or any of its related projects in the Kivy ecosystem? Is there an error you don’t understand? Are you trying to figure out how to use it? We have volunteers who can help!

The best channels to contact us for support are listed in the latest Contact Us document.

Contributing

PyJNIus is part of the Kivy ecosystem - a large group of products used by many thousands of developers for free, but it is built entirely by the contributions of volunteers. We welcome (and rely on) users who want to give back to the community by contributing to the project.

Contributions can come in many forms. See the latest Contribution Guidelines for how you can help us.

Code of Conduct

In the interest of fostering an open and welcoming community, we as contributors and maintainers need to ensure participation in our project and our sister projects is a harassment-free and positive experience for everyone. It is vital that all interaction is conducted in a manner conveying respect, open-mindedness and gratitude.

Please consult the latest Code of Conduct.

Contributors

This project exists thanks to all the people who contribute. [Become a contributor].

Backers

Thank you to all of our backers! 🙏 [Become a backer]

Sponsors

Special thanks to all of our sponsors, past and present. Support this project by [becoming a sponsor].

Here are our top current sponsors. Please click through to see their websites, and support them as they support us.

pyjnius's People

Contributors

akshayaurora avatar amirouche avatar amsukdu avatar andremiras avatar benson-basis avatar bimargulies avatar brandonherzog avatar cheaterman avatar chrisjrn avatar cmacdonald avatar danielepantaleone avatar dessant avatar drmoose avatar hadim avatar hx2a avatar inclement avatar invalidco avatar jrnp97 avatar kevlened avatar keyweeusr avatar kived avatar lenbok avatar lilyfoote avatar misl6 avatar obfusk avatar psader avatar thopiekar avatar tito avatar tshirtman avatar zielmicha avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyjnius's Issues

Tests don't pass (doesn't find libraries)

Hi,

I'm trying to run pyjnius on Debian wheezy. The vast majority of the tests (make tests) fails. It seems to be (mostly) related to the fact that it doesn't find the jars required for the tests. The failure looks like this:

======================================================================
ERROR: test_instance_methods (test_basics.BasicsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/michael/hacking/testkraut/db/pyjnius/tests/test_basics.py", line 31, inn test_instance_methods
    test = autoclass('org.jnius.BasicsTest')()
  File "/home/michael/hacking/testkraut/db/pyjnius/jnius/reflect.py", line 109, in autoclass
    c = find_javaclass(clsname)
  File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:7418)
JavaException: Class not found 'org/jnius/BasicsTest'

I can work with the standard library without problems:

>>> from jnius import autoclass
>>> autoclass('java.lang.System').out.println('Hello world')
Hello world

but accessing any other JAR fails.

I tried Debian's openjdk 6 and 7 -- the result is the same. It there any (versioned) dependency that I am missing?

Compilation Error

I'm trying to install python for android, but it gets caught up at this point and I've tried everything to get around it... Fails on jnius compilation. Anyone have a similar issue?

Leaving ARM enviromnent
Call build_pyjnius
Entering in ARM enviromnent
Compiler found at /opt/android-ndk/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc
/home/eric/workspace/python-for-android/build/python-install/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running build_ext
building 'jnius' extension
arm-linux-androideabi-gcc -mandroid -fomit-frame-pointer --sysroot /opt/android-ndk//platforms/android-14/arch-arm -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -mandroid -fomit-frame-pointer --sysroot /opt/android-ndk//platforms/android-14/arch-arm -fPIC -I/home/eric/workspace/python-for-android/build/python-install/include/python2.7 -c jnius/jnius.c -o build/temp.linux-x86_64-2.7/jnius/jnius.o
jnius/jnius.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation.
error: command 'arm-linux-androideabi-gcc' failed with exit status 1
find: `cython': No such file or directory
/home/eric/workspace/python-for-android/build/python-install/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running build_ext
building 'jnius' extension
arm-linux-androideabi-gcc -mandroid -fomit-frame-pointer --sysroot /opt/android-ndk//platforms/android-14/arch-arm -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -mandroid -fomit-frame-pointer --sysroot /opt/android-ndk//platforms/android-14/arch-arm -fPIC -I/home/eric/workspace/python-for-android/build/python-install/include/python2.7 -c jnius/jnius.c -o build/temp.linux-x86_64-2.7/jnius/jnius.o
jnius/jnius.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation.
error: command 'arm-linux-androideabi-gcc' failed with exit status 1

JNI ERROR (app bug): local reference table overflow (max=512)

Loading some classes on android simply break because of the limit of jni reference table, would be great to find a way around this.

Exemple found just now, that crashes kivy-remote-shell on its own.

>>> from jnius import autoclass
>>> WebView = autoclass('android.webkit.WebView')

Connection to 192.168.0.10 closed by remote host.

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362797-jni-error-app-bug-local-reference-table-overflow-max-512?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).

pyjnius is still not thread-safe?

Hi, All
I have to invoke a static java method in my task(django-celery) through pyjnius. It works fine for the first task. But it throws exception while executing the 2nd task. Check the jvm log, it shows

Internal exceptions (1 events):
Event: 0.058 Thread 0x0000000001ae2800 Threw 0x0000000704a06140 at /build/buildd/openjdk-7-7u25-2.3.10/build/openjdk/hotspot/src/share/vm/prims/jni.cpp:3994

Seems this is thread problem, right?
How can i fix this?

BTW, misja, can i make it works through gevent?

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362782-pyjnius-is-still-not-thread-safe?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).

JavaException: JVM exception occured

I get a JVM error while trying to create a Toast. Example code from Kivy Remote:

from jnius import autoclass
AndroidString = autoclass('java.lang.String')
PythonActivity = autoclass('org.renpy.android.PythonActivity')
Toast = autoclass('android.widget.Toast')
msg = AndroidString("Hello, world!".encode('utf-8'))
toast = Toast.makeText(PythonActivity.mActivity, msg, Toast.LENGTH_SHORT)
CHECK FOR org/renpy/android/PythonActivity android/content/Context True
CHECK FOR java/lang/String java/lang/CharSequence True
Traceback (most recent call last):
File "", line 1, in
File "jnius_export_class.pxi", line 751, in jnius.jnius.JavaMultipleMethod.call (jnius/jnius.c:14919)
File "jnius_export_class.pxi", line 508, in jnius.jnius.JavaMethod.call (jnius/jnius.c:12495)
File "jnius_export_class.pxi", line 665, in jnius.jnius.JavaMethod.call_staticmethod (jnius/jnius.c:13745)
File "jnius_utils.pxi", line 40, in jnius.jnius.check_exception (jnius/jnius.c:1855)
JavaException: JVM exception occured

cython can't find jni.pxi

Installing collected packages: jnius
  Running setup.py install for jnius
    cythoning jnius/jnius.pyx to jnius/jnius.c

    Error compiling Cython file:
    ------------------------------------------------------------
    ...
        'JavaObject', 'JavaClass', 'JavaMethod', 'JavaField', 'MetaJavaClass',
        'JavaException', 'cast', 'find_javaclass')

    from libc.stdlib cimport malloc, free

    include "jni.pxi"
    ^
    ------------------------------------------------------------

from .jnius import * --> No module named jnius

I compile jnius on MS Win 8 ( 64ibt ). The Python ver. is 2.7 ( 32bit ). The Oracle Java JDK ver. is 1.7.0_25 ( 32bit ) The C/C++ compiler was TDM-GCC 4.7 ( 32bit )
After some hack, I finish the compile process and install the egg
If I kept the jnius.pyd as original name, the Python intepreter complain no dll loaded
If I rename the jnius.pyd to jnius.dll, the Python interpreter complained No module named jnius.

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362783-from-jnius-import-no-module-named-jnius?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).

Memory leak in constructor

Local reference returned from NewObjectA is not deleted.

(I would make pull request, but it looks like it's not possible to have two at once)

git pull: https://github.com/zielmicha/pyjnius/

or patch:

diff --git a/jnius/jnius_export_class.pxi b/jnius/jnius_export_class.pxi
index 790d967..a62a913 100644
--- a/jnius/jnius_export_class.pxi
+++ b/jnius/jnius_export_class.pxi
@@ -225,6 +225,7 @@ cdef class JavaClass(object):
                     self.__javaclass__))

             self.j_self = create_local_ref(j_env, j_self)
+            j_env[0].DeleteLocalRef(j_env, j_self)
         finally:
             if j_args != NULL:
                 free(j_args)

java.sql.Connection.unwrap throws JavaException: Invalid python object for this argument

Running this code under Jython works. Running the equivalent Java works. I'm doing it just as the docs say to. But PyJNIus prints:

Traceback (most recent call last):
  File "test.py", line 25, in <module>
    olapConnection = connection.unwrap(OlapConnection)
  File "jnius_export_class.pxi", line 487, in jnius.JavaMethod.__call__ (jnius/jnius.c:11969)
  File "jnius_conversion.pxi", line 58, in jnius.populate_args (jnius/jnius.c:4110)
jnius.JavaException: Invalid python object for this argument. Want 'java/lang/Class', got <class 'jnius.reflect.org.olap4j.OlapConnection'>

for the following code:

import sys

_is_jython = sys.platform.startswith("java")
if _is_jython:
    from java.sql import DriverManager
    from org.olap4j import OlapConnection
else:
    from jnius import autoclass
    DriverManager = autoclass('java.sql.DriverManager')
    OlapConnection = autoclass('org.olap4j.OlapConnection')


url = "jdbc:mondrian:JdbcDrivers=org.postgresql.Driver;Jdbc=jdbc:postgresql://localhost/foodmart?user=postgres&password=password;Catalog=demo/FoodMart.xml;"

mdx = '''
SELECT
  [Measures].[Customer Count] ON COLUMNS,
  [Gender].[Gender].Members ON ROWS
FROM [Sales]
'''

connection = DriverManager.getConnection(url)
olapConnection = connection.unwrap(OlapConnection)
result = olapConnection.prepareOlapStatement(mdx).executeQuery()

(To run the test code, use same setup procedure as bug #21.)

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Java Iterables

Programming in python based on lists and other collections. I think it's better to convert them instantly. I mean you should reduce switching between python and JVM. Take a look at this example:

while iterator.hasNext():
    print iterator.next()

That needs switching to JVM for each item. But there isn't any need if you convert Java Iterable to python list. Or this one with same performance issue:

for i in range(arr.length):
    print list[i]

How to navigation buttons

I have a kivy app that needs to close threads pythonically when exited, but when the user touches the back or home buttons on the navigation bar the app freezes because the python activity did not get a proper exit() call and thus the threads keep running. Since Android does not allow for the Nav bar to be disabled I need a work around for this. I'm thinking that using PyJnius I can have a 'os._exit(True)' called when the backbutton is pressed. The only thing is I have no idea how I would do this. I came here to ask the question because I don't know of a forum where I could ask. Thank you for any help!

Inheriting from Java classes doesn't work

Part of the problem is that JavaMetaClass.new assumes that it will always be called to create a proxy, when it will be called for every descendant class. On the same line, handling of the jclass_registry must be restricted to actual proxies. Something else I found is that the treatment of objects returned from Java is lax, which makes it impossible to pass them back to Java methods.

I can work on some of this issues in due time.

I very much like how fast jnius is at loading Java, and being able to use the latest versions of Python.

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362796-inheriting-from-java-classes-doesn-t-work?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).

How do I install it?

I have no idea where to begin installing this. I want to use it with kivy on android for the tts module. I can't find any documentation except for how to use it after it's installed. I tried using 'make' but my system doesn't recognize the 'make' command even after installing make. Need more detail on this. Maybe step by step (including installing make).

Output parameters don't works

Hi,
There are some problems with ouput arguments. If I write, for example :

String = autoclass('java.lang.String')
string = String("word".encode('utf-8'))
btarray= [0]*4
string.getBytes(0,4,btarray,0)
print btarray

It output :

[0, 0, 0, 0]

So the output argument(btarray) is not written
Same with :

[.....]
usbConnection = cast('android.hardware.usb.UsbDeviceConnection', UsbManager.openDevice(dev))
response= [0]*4
usbConnection.bulkTransfer(epIN, response, 4, 1000); # Try to read from USB (Host Mode API)
print response

If I use a bytearray (btarray=bytearray()), I get this error :

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/sdcard/testAn.py", line 13, in <module>
    string.getBytes(0,4,btarray,0)
  File "jnius_export_class.pxi", line 813, in jnius.jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:17292)
JavaException: No methods matching your arguments

And if I use a list (btarray=list()), I get this :

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/sdcard/testAn.py", line 13, in <module>
    string.getBytes(0,4,btarray,0)
  File "jnius_export_class.pxi", line 819, in jnius.jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:17414)
  File "jnius_export_class.pxi", line 577, in jnius.jnius.JavaMethod.__call__ (jnius/jnius.c:15021)
  File "jnius_export_class.pxi", line 658, in jnius.jnius.JavaMethod.call_method (jnius/jnius.c:15691)
  File "jnius_utils.pxi", line 39, in jnius.jnius.check_exception (jnius/jnius.c:2200)
JavaException: JVM exception occured

Thanks a lot.

Problem on 64 bit ubuntu 12.04

Make seems to be looking in the wrong place for some of the java libs (or a place I don't have them).

(2d)stu@beezlebub:~/projects/external/pyjnius$ ls /usr/lib/jvm/jdk1.7.0_04/
bin  COPYRIGHT  db  include  jre  lib  LICENSE  man  README.html  release  src.zip  THIRDPARTYLICENSEREADME.txt
(2d)stu@beezlebub:~/projects/external/pyjnius$ ls /usr/lib/jvm/jdk1.7.0_04/lib/
ct.sym  dt.jar  ir.idl  jconsole.jar  jexec  orb.idl  sa-jdi.jar  tools.jar  visualvm
(2d)stu@beezlebub:~/projects/external/pyjnius$ 

Here's the output of make

(2d)stu@beezlebub:~/projects/external/pyjnius$ make
python setup.py build_ext --inplace -f
/usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
  warnings.warn(msg)
running build_ext
building 'jnius' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/lib/jvm/jdk1.7.0_04/include -I/usr/lib/jvm/jdk1.7.0_04/include/linux -I/usr/include/python2.7 -c jnius/jnius.c -o build/temp.linux-x86_64-2.7/jnius/jnius.o
jnius/jnius.c: In function ‘__pyx_pf_5jnius_13MetaJavaClass_2resolve_class’:
jnius/jnius.c:7025:13: warning: variable ‘__pyx_v_meta’ set but not used [-Wunused-but-set-variable]
jnius/jnius.c: In function ‘__pyx_pf_5jnius_9JavaField___cinit__’:
jnius/jnius.c:9458:13: warning: variable ‘__pyx_v_definition’ set but not used [-Wunused-but-set-variable]
jnius/jnius.c: In function ‘__pyx_pf_5jnius_10JavaMethod___cinit__’:
jnius/jnius.c:11061:13: warning: variable ‘__pyx_v_definition’ set but not used [-Wunused-but-set-variable]
jnius/jnius.c: In function ‘__pyx_pf_5jnius_18JavaMultipleMethod___cinit__’:
jnius/jnius.c:13182:13: warning: variable ‘__pyx_v_definition’ set but not used [-Wunused-but-set-variable]
gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/jnius/jnius.o -L/usr/lib/jvm/jdk1.7.0_04/lib/amd64/server -ljvm -o /home/stu/projects/external/pyjnius/jnius/jnius.so -Wl,-rpath /usr/lib/jvm/jdk1.7.0_04/lib/amd64/server
gcc: error: /usr/lib/jvm/jdk1.7.0_04/lib/amd64/server: No such file or directory
error: command 'gcc' failed with exit status 1
make: *** [build_ext] Error 1
(2d)stu@beezlebub:~/projects/external/pyjnius$ 

pyjnius is not thread-safe

The following results in a core dump:

import threading
from jnius import autoclass

class MyThread(threading.Thread):
    def run(self):
        autoclass('java.lang.System').out.println('Hello world')

for i in range(2):
    MyThread().start()

Setting JVM options

Is there any way to set JVM heap size? something that works like this:

java -Xmx512m

And there are some questions about CLASSPATH. When I set it in code, can't find my classes:

environ['CLASSPATH'] = 'absolute/path/file.jar'

Even setting that out of my python file, doesn't change anything:

export CLASSPATH="absolute/path/file.jar"

lookup_java_object_name leaks LocalRefs

Actually manages to leak 3 references each call!

git pull https://github.com/zielmicha/pyjnius

Or patch:

diff --git a/jnius/jnius_utils.pxi b/jnius/jnius_utils.pxi
index 7d893b4..05d54f7 100644
--- a/jnius/jnius_utils.pxi
+++ b/jnius/jnius_utils.pxi
@@ -77,6 +77,9 @@ cdef bytes lookup_java_object_name(JNIEnv *j_env, jobject j_obj):
     cdef jmethodID jmeth = j_env[0].GetMethodID(j_env, jcls2, 'getName', '()Ljava/lang/String;')
     cdef jobject js = j_env[0].CallObjectMethod(j_env, jcls, jmeth)
     name = convert_jobject_to_python(j_env, b'Ljava/lang/String;', js)
+    j_env[0].DeleteLocalRef(j_env, js)
+    j_env[0].DeleteLocalRef(j_env, jcls)
+    j_env[0].DeleteLocalRef(j_env, jcls2)
     return name.replace('.', '/')

JavaException when calling Java methods stored in Python class variables

I ran across a confusing JavaException when trying to call a Java method stored in a class variable:

from jnius import autoclass                                                     

System = autoclass('java.lang.System')                                          

# This works:                                                                   
System.out.println('Hello World')                                               
map(System.out.println, ['Hello World'])                                        
println = System.out.println                                                    
map(println, ['Hello World'])                                                   

class MyClass(object):                                                          
    def __init__(self):                                                         
        self.println = System.out.println  # Instance variables are fine                                      
map(MyClass().println, ['Hello World'])                                         

# This causes an exception:                                                                 
class MyClass(object):                                                          
    println = System.out.println  # But class variables cause errors                                          
map(MyClass.println, ['Hello World'])

Running this code produces the following output:

Hello World
Hello World
Hello World
Hello World
Traceback (most recent call last):
  File "jniustest.py", line 19, in <module>
    map(MyClass.println, ['Hello World'])
  File "jnius_export_class.pxi", line 745, in jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:15502)
jnius.JavaException: No methods matching your arguments

This is an odd edge-case with an easy workaround (don't store Java methods in class variables), but I thought I'd report it here in case anyone else encounters it.

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362787-javaexception-when-calling-java-methods-stored-in-python-class-variables?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).

doesn't work on windows

was trying to compile it with mingw and vc 2008, but even after adding the correct includes from the jdk (subdir "win32"), I get this error:

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG "-Ic:\Program Files (x86)\Java\jdk1.7.0_05\include" "-Ic:\Program Files (x86)\Java\jdk1.7.0_05\include\win32" -IC:\Python27\include -IC:\Python27\PC /Tcjnius\jnius.c /Fobuild\temp.win32-2.7\Release\jnius\jnius.obj
jnius.c
jnius\jnius.c(961) : error C2373: 'JNI_CreateJavaVM': Neudefinition; unterschiedliche Modifizierer
c:\Program Files (x86)\Java\jdk1.7.0_05\include\jni.h(1938): Siehe Deklaration von 'JNI_CreateJavaVM'

Accessing Android's clipboard

I'm trying to access Android's clipboard using jnius, but I'm running into some issues. So far I've tried the following:

if platform() == 'android':
    from jnius import autoclass
    Context = autoclass('org.renpy.android.PythonActivity')
    ClipboardManager = autoclass('android.content.ClipboardManager')
    ClipData = autoclass('android.content.ClipData')
    ClipDescription = autoclass('android.content.ClipDescription')
    ClipItem = autoclass('android.content.ClipData.Item') #it throws an error saying that the class was not found
    context = Context.mActivity
    vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) #vibrator implementation works very well, thans tshirtman!
    android_clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE)

I then tried putting data to the clipboard using an example provided here (http://developer.android.com/guide/topics/text/copy-paste.html):

clip = ClipData.newPlainText("simple text","Hello, World!") #it throws an error saying that it was expecting java/lang/charsequence' but got 'simple text'
android_clipboard.setPrimaryClip(clip)

Is it actually possible to access the aforementioned classes through pyjnius. If yes, what am I doing wrong in the implementation. Thanks for any help.

JDBC unwrapping doesn't work

Problem

I'm using Olap4j, and, as documented on page 11 of this PDF, Java is supposed to automatically unwrap JDBC connection objects to gain access to their true connection, which works under Jython but not PyJNIus. (This seems like magic to me, so I don't understand the details.)

Steps to reproduce

  1. Download Pentaho Mondrian. Create a Postgres table called 'foodmart', username 'postgres', password 'password'. You may need to load the sample data as described in the Mondrian documentation.
  2. Create the test.py file given at the bottom of this report in the Mondrian directory. Run it. Under Jython 2.7, it runs fine, but under PyJNIus, it reports:
Traceback (most recent call last):
  File "test.py", line 23, in <module>
    result = connection.prepareOlapStatement(mdx).executeQuery()
AttributeError: 'java.sql.Connection' object has no attribute 'prepareOlapStatement'

test.py:

import sys

_is_jython = sys.platform.startswith("java")
if _is_jython:
    from java.sql import DriverManager
    from org.olap4j import OlapConnection
else:
    from jnius import autoclass
    DriverManager = autoclass('java.sql.DriverManager')
    OlapConnection = autoclass('org.olap4j.OlapConnection')


url = 'jdbc:mondrian:JdbcDrivers=org.postgresql.Driver;Jdbc=jdbc:postgresql://localhost/foodmart?user=postgres&password=password;Catalog=demo/FoodMart.xml;'

mdx = '''
SELECT
  [Measures].[Customer Count] ON COLUMNS,
  [Gender].[Gender].Members ON ROWS
FROM [Sales]
'''

connection = DriverManager.getConnection(url)
result = connection.prepareOlapStatement(mdx).executeQuery()

JNI-style signatures are ugly, change the api of interfaces to use a more java-like interface.

example:

@java_method('(ILjava/lang/Object;)Ljava/lang/Object;')

if you don't know jni, this is impossible to understand/write correctly.

something like

from jnius import Object, Int
@java_method((Int, Object), Object)

maybe?

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362781-jni-style-signatures-are-ugly-change-the-api-of-interfaces-to-use-a-more-java-like-interface?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).

setup.py jre_home

This section doesn't return a good jre_home on my box. What's an example of the properly formed directory? I have several Java installations going.

jre_home = environ.get('JRE_HOME')
if not jre_home:
    jre_home = subprocess.Popen('readlink -f /usr/bin/java | sed "s:bin/java::"',
            shell=True, stdout=subprocess.PIPE).communicate()[0].strip()

cython error

I have the following errors with the latest version:

python setup.py build_ext --inplace -f
/usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running build_ext
cythoning jnius/jnius.pyx to jnius/jnius.c

Error compiling Cython file:

...
#XXX not working with cython?
#jint (RegisterNatives)(JNIEnv, jclass, const_JNINativeMethod_, jint)
jint (UnregisterNatives)(JNIEnv, jclass)
jint (MonitorEnter)(JNIEnv, jobject)
jint (MonitorExit)(JNIEnv, jobject)
jint (GetJavaVM)(JNIEnv, JavaVM_*)

^

/home/desnos/python/pyjnius/jnius/jni.pxi:375:42: 'JavaVM' is not a type identifier

Error compiling Cython file:

...
jboolean JNI_FALSE
ctypedef struct JavaVMInitArgs:
jint version
jint nOptions
jboolean ignoreUnrecognized
JavaVMOption *options

^

/home/desnos/python/pyjnius/jnius/jnius_jvm_desktop.pxi:12:8: 'JavaVMOption' is not a type identifier

Error compiling Cython file:

...
j_env[0].ExceptionClear(j_env)
raise JavaException('JVM exception occured')

cdef dict assignable_from = {}
cdef void check_assignable_from(JNIEnv *env, JavaClass jc, bytes signature) except *:

^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:44:45: 'JavaClass' is not a type identifier

Error compiling Cython file:

...
cdef dict assignable_from = {}
cdef void check_assignable_from(JNIEnv *env, JavaClass jc, bytes signature) except *:
cdef jclass cls

# if we have a JavaObject, it's always ok.
if signature == 'java/lang/Object':
            ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:48:17: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
cls = env[0].FindClass(env, signature)
if cls == NULL:
raise JavaException('Unable to found the class for {0!r}'.format(
signature))

    result = bool(env[0].IsAssignableFrom(env, jc.j_cls, cls))
                                                ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:66:53: Cannot convert Python object to 'jclass'

Error compiling Cython file:

...

for index in range(len(sign_args)):
    r = sign_args[index]
    arg = args[index]

    if r == 'Z':
        ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:103:13: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
if not isinstance(arg, bool):
return -1
score += 10
continue

    if r == 'B':
        ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:109:13: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
if not isinstance(arg, int):
return -1
score += 10
continue

    if r == 'C':
        ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:115:13: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
if not isinstance(arg, str) or len(arg) != 1:
return -1
score += 10
continue

    if r == 'S' or r == 'I' or r == 'J':
        ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:121:13: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
if not isinstance(arg, str) or len(arg) != 1:
return -1
score += 10
continue

    if r == 'S' or r == 'I' or r == 'J':
                    ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:121:25: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
if not isinstance(arg, str) or len(arg) != 1:
return -1
score += 10
continue

    if r == 'S' or r == 'I' or r == 'J':
                                ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:121:37: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
score += 5
continue
else:
return -1

    if r == 'F' or r == 'D':
        ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:131:13: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
score += 5
continue
else:
return -1

    if r == 'F' or r == 'D':
                    ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:131:25: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
if arg is None:
score += 10
continue

        # if it's a string, accept any python string
        if r == 'java/lang/String' and isinstance(arg, basestring):
            ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:150:17: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
score += 10
continue

        # if it's a generic object, accept python string, or any java
        # class/object
        if r == 'java/lang/Object':
            ^

/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:156:17: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
cdef bytes r = definition[1:-1]
cdef JavaObject ret_jobject
cdef JavaClass ret_jc

# we got a generic object -> lookup for the real name instead.
if r == 'java/lang/Object':
    ^

/home/desnos/python/pyjnius/jnius/jnius_conversion.pxi:82:9: Comparisons between bytes/unicode and str are not portable to Python 3

Error compiling Cython file:

...
# we got a generic object -> lookup for the real name instead.
if r == 'java/lang/Object':
r = lookup_java_object_name(j_env, j_object)

# if we got a string, just convert back to Python str.
if r == 'java/lang/String':
    ^

/home/desnos/python/pyjnius/jnius/jnius_conversion.pxi:86:9: Comparisons between bytes/unicode and str are not portable to Python 3
building 'jnius' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/lib/jvm/java-6-sun-1.6.0.26/include -I/usr/lib/jvm/java-6-sun-1.6.0.26/include/linux -I/usr/include/python2.7 -c jnius/jnius.c -o build/temp.linux-x86_64-2.7/jnius/jnius.o
jnius/jnius.c:1:2: erreur: #error Do not use this file, it is the result of a failed Cython compilation.
error: command 'gcc' failed with exit status 1
make: *** [build_ext] Erreur 1

array of bytes

I have a question, what is the best way to create an array of bytes ?

with a python list ?

In [1]: from jnius import autoclass

In [2]: byte_class = autoclass('java.lang.Byte')

In [3]: [byte_class(50), byte_class(60)]
Out[3]:
[<java.lang.Byte at 0x2296d70 jclass=java/lang/Byte jself=<jnius.LocalRef object at 0x19016e8>>,
<java.lang.Byte at 0x2296e30 jclass=java/lang/Byte jself=<jnius.LocalRef object at 0x1901698>>]

Thx !

JavaException: Unable to found the class for 'java/lang/CharSequence'

I'm trying to get Toast working with jnius, but I can't get past java.lang.CharSequence. From a Kivy Remote Console session:

>>> from jnius import autoclass 
>>> PythonActivity = autoclass('org.renpy.android.PythonActivity') 
>>> Toast = autoclass('android.widget.Toast') 
>>> toast = Toast(PythonActivity.mActivity) 
>>> toast.setText("Hello, world") 
Traceback (most recent call last): 
  File "<console>", line 1, in <module> 
  File "jnius_export_class.pxi", line 745, in jnius.jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:14793) 
JavaException: No methods matching your arguments
>>> JavaString = autoclass('java.lang.String') 
>>> msg = JavaString("Hello, world") 
>>> toast.setText(msg) 
Traceback (most recent call last): 
  File "<console>", line 1, in <module> 
  File "jnius_export_class.pxi", line 751, in jnius.jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:14919) 
  File "jnius_export_class.pxi", line 503, in jnius.jnius.JavaMethod.__call__ (jnius/jnius.c:12462) 
  File "jnius_conversion.pxi", line 51, in jnius.jnius.populate_args (jnius/jnius.c:3987) 
  File "jnius_utils.pxi", line 63, in jnius.jnius.check_assignable_from (jnius/jnius.c:2037) 
JavaException: Unable to found the class for 'java/lang/CharSequence' 

Link Python GC to Java GC for PythonJavaClass

Take a look at this snippet:

class DelayedRunnable(PythonJavaClass):
    __javainterfaces__ = ['java/lang/Runnable']
    def __init__(self, callback, *args, **kwargs):
        super(DelayedRunnable, self).__init__(*args, **kwargs)
        self.callback = callback
    @java_method('()V')
    def run(self):
        self.callback()


handler = Handler(Looper.getMainLooper())
handler.postDelayed(DelayedRunnable(init_receiver), 1000)

The DelayedRunnable() instance will be deleted by Python GC, before java use it.

This is why we can have than kind of weirdness:

I/python  (25412): !! create_proxy_instance() on 1548769344 <__main__.DelayedRunnable object at 0x5c505840>
...
I/python  (25412): !! invoke0() from (1548769344, 1548769344) ('', 'system', 'dock', 'multi')
I/python  (25412):  Exception AttributeError: "'tuple' object has no attribute 'invoke'" in 'jnius.jnius.invoke0' ignored

We need to keep a reference of the DelayedRunnable until the java proxy is really deleted. Keeping a reference is not an issue, detecting when to release it is the issue.

Maybe http://docs.oracle.com/javase/6/docs/api/java/lang/ref/PhantomReference.html could help us, but i'm not sure about how to use it.

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362784-link-python-gc-to-java-gc-for-pythonjavaclass?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).

Can not find class with www-data account

Hi Pyjnius,

Thank you for this great project. It save me a lot of time.

I use it with django. It works fine at develop mode, the normal linux account + django builtin web server.
I mean use command line as 'python manage.py runserver'

However, It failed to invoke my java class in same folder, at apache mode + mod_wsgi. The exception message is 'Class XXX not found'. But the 'java.lang.System' class can be found easily.

I checked the python os.environ between dev mode and apache mode.

Can you help me?

Thanks a lot.

Doesn't work under Windows 7

C:\Python27x64\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running install
running build
running build_py
running build_ext
skipping 'jnius\jnius.c' Cython extension (up-to-date)
building 'jnius' extension
C:\MinGW32\bin\gcc.exe -mno-cygwin -mdll -O -Wall -DMS_WIN64 -I/usr/include -I/usr/include\linux -IC:\Python27x64\include -IC:\Python27x64\PC -c jnius\jnius.c -o build\temp.win-amd64-2.7\Release\jnius\jnius.o
cc1.exe: error: unrecognized command line option '-mno-cygwin'
error: command 'gcc' failed with exit status 1

[armhf] - Builds fail on launchpad

As builds were working at the beginning I was wondering why it now fails to build.

As you can see here: https://launchpad.net/~kivy-team/+archive/kivy-daily/+build/4275170
(build log included)

After checking the setup.py for a while I found the reason at
https://github.com/kivy/pyjnius/blob/master/setup.py#L68

Which just cares about i386 and amd64. What about using platform.machine()?
In case of armel and armhf we would need to add a dict to point at the folder "arm", but this isn't really a problem.
Also x86_64 would be needed to be translated to amd64.

Cast python object to a Java Object

my code raises

raise JavaException('Invalid python object for this '
                        'argument. Want {0!r}, got {1!r}'.format(
                            argtype[1:-1], py_arg))

https://github.com/kivy/pyjnius/blob/master/jnius/jnius_conversion.pxi#L58

Can I "cast/wrap" my python object which can be one of the following str, unicode, list, int, float, long (and dict in the future) to/in a Java Object so that I don't have to explicitly do a switch like the following:

if isinstance(my_object, str):
    my_object = java.lang.String(my_object)
# etc...

README accelerometer example code out of date?

The accelerometer example in README.md seems wrong (out of date?). Specifically, it seems Hardware.accelerometerEnable() should be Hardware.accelerometerEnable(True) - the former fails on android with a message about incorrect number of arguments.

Ship binary versions of Jnius

Neo4J is ready to use jnius as the binding library of its python library if its possible to ship it in binary format.

I guess it's possible, it should be shipped at least for Windows 32bit/64bit against Java 6 (if it matters) and Unix-like 32bits/64bits, MacOS X should be supported too.

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Can't install at Macosx lion

When I install the pyjnius by pip, I get the JDK 7 and install it. then when I run pip install pyjnius, it's report the error as /Library/Java/JavaVirtualMachines/jdk1.7.0_06.jdk/Contents/Home/include/jni.h:45:10: fatal error: 'jni_md.h' file not found (after I has set the JDK_HOME and JRE_HOME)

And I find the file at '/Library/Java/JavaVirtualMachines/jdk1.7.0_06.jdk/Contents/Home/include/darwin/` and copy it to parent directory.

Then, I retry installing, and get the result like clang: error: no such file or directory: '/Library/Java/JavaVirtualMachines/jdk1.7.0_06.jdk/Contents/Home/jre/lib/amd64/server'.
I can't find the ire/lib/amd64/server. what can I do?

pyjnius does not seems to be installed properly in osx 10.6

modified the setup.py to include the following properties
library_dirs = ['/System/Library/Frameworks/JavaVM.framework/Libraries']
include_dirs = ['/System/Library/Frameworks/JavaVM.framework/Headers']

[15:39:24][/usr/local/pyjnius]> python2.7 setup.py install
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running install
running build
running build_py
running build_ext
skipping 'jnius/jnius.c' Cython extension (up-to-date)
running install_lib
running install_egg_info
Removing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jnius-1.1_dev-py2.7.egg-info
Writing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jnius-1.1_dev-py2.7.egg-info

[15:39:51][/usr/local/pyjnius]> ls -al /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jnius-1.1_dev-py2.7.egg-info
-rw-r--r-- 1 felixgao admin 829 Oct 9 15:39 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jnius-1.1_dev-py2.7.egg-info

[15:43:07][/usr/local/pyjnius]> python2.7
Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

from jnius import *
Traceback (most recent call last):
File "", line 1, in
File "jnius/init.py", line 12, in
from .jnius import *
ImportError: No module named jnius

varargs don’t seem to work

>>> from jnius import autoclass
>>> syso = autoclass('java.lang.System').out
>>> syso.println("hi")
hi
>>> syso.printf("hi\n")
/usr/lib/python2.7/site-packages/jnius/jnius.so in jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:14462)()
JavaException: No methods matching your arguments
>>> syso.printf("hi %s\n", "jnius")
/usr/lib/python2.7/site-packages/jnius/jnius.so in jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:14462)()
JavaException: No methods matching your arguments

no multidimensional array support

testcase:

>>> DB = autoclass("java.awt.image.DataBufferDouble")
>>> DB([[.5]], 1)
JavaException: No constructor matching your arguments
>>> db = DB(1)
>>> db.getBankData()
JavaException: Invalid return definition for array

both errors shouldn’t happen, both are due to the fact that both convert_pyarray_to_java and convert_jarray_to_python can receive a definition starting with "[", i.e. a multidimensional array. e.g. the above function getBankData has the return type signature [[D, so convert_jarray_to_python(j_env, "[D", j_object) is called and fails.

an idea for convert_jarray_to_python would be to insert another elif r=="[" and calling convert_jarray_to_python recursively inside.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.