Giter Site home page Giter Site logo

nativelibs4java / bridj Goto Github PK

View Code? Open in Web Editor NEW
296.0 296.0 77.0 23.92 MB

BridJ: blazing fast Java / C / C++ interop

Home Page: https://code.google.com/archive/p/bridj/

License: Other

Shell 1.71% Makefile 0.14% C 8.90% Java 85.09% C++ 2.76% Objective-C 0.54% Assembly 0.42% CMake 0.44%

bridj's Introduction

This repository (used to) host / incubated source code for the following (related) projects :

Please read Olivier Chafik's blog for announcements.

bridj's People

Contributors

alagopus avatar ctrimble avatar finson avatar gitter-badger avatar jlleitschuh avatar mkw avatar ochafik avatar rkraneis avatar sarxos avatar twitwi avatar vampire avatar washley 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

bridj's Issues

[BridJ] SEVERE: Failed to get address of method

From @finson on February 16, 2012 5:10

Olivier: Thank you for the Issue #261 fix. I cleaned my local maven repo, pulled all the recent git changes into nl4j, regenerated the libraries (not including Scala related because Scalaxy build hangs with 100% CPU ...), and tried to run again. I now get the following:

SEVERE: Failed to get address of method public static native org.bridj.Pointer org.bridj.dyncall.DyncallLibrary.dcNewStruct(long,int)

and the same error for 'dcCloseStruct, dcStructSize, dcSubStruct, dcStructField, dcStructAlignment, dcFreeStruct, and dcDefineStruct'. Looking at DyncallLibrary.java, last updated Dec 31, 2011, those methods are there in their Java form. However, they don't appear to be present in the bridj.dll that I have from the github repo which was last updated on Jan 02, 2012. Is it possible that bridj.dll was generated from an out of date header? Thanks.

Copied from original issue: nativelibs4java/nativelibs4java#262

Memory consumption by Pointer allocations.

From @haron4igg on May 27, 2013 20:26

Hi Olivier,

I'm working with continuos calculations, which producing a lot of double arrays from C library. Using BridJ caused to real memory consumption problem.

By VisualVM tool i figured out that all allocated and released pointers are still exist in memory and being garbaged only after manual invocation of GC.

Here it is my code, may be i did something wrong..:

NativeCalculatorLibrary.OutputCallback callback = new NativeCalculatorLibrary.OutputCallback() {
@OverRide
public void apply(double v, Pointer doubles, double v2) {
if (doubles != null && listener != null) {
double [] input = doubles.getDoubles(dimension);
listener.onReceivePoints(v, input, v2);
doubles.release();
}
}
};

I had a similar problem with JNI, but it was fixed by deleting local environment reference after performing callback.

Thank you in advance,
Igor.

Copied from original issue: nativelibs4java/nativelibs4java#404

Bridj problems passing double under armhf

From @jonhare on September 16, 2014 20:52

Hi Olivier,

I've had a few reports of strange issues with the OpenIMAJ webcam library not working properly on linux boards using the armhf ABI (@sarxos also has a load of issues with his webcam project where the openimaj library is failing under armhf - see e.g. sarxos/webcam-capture#244).

I spent the day debugging, and have narrowed the problem down to the passing of double values. For some reason, if you try to pass a double value as a function/method argument from the Java side to the native side, the value will not be correctly passed, and the stack will be corrupted (noticeable in particular through subsequent arguments not having the correct values either, before the ensuing SEGFAULT).

I've made a very simple test case here: http://users.ecs.soton.ac.uk/jsh2/testcase.tgz
The test case contains a native library (sources in src/main/cpp) with a single method that takes a single double and prints it; the java code just wraps the native lib and calls the function with the double value 101.101. What we'd expect to happen is for 101.101000 to be printed, but instead we get 0.0. I've tested under an older armel JVM (using bridj 0.6.3-SNAPSHOT), and the code works as expected, so this definitely appears to be a specific problem with the armhf abi.

I don't know enough about the internals of bridj, but I wonder if the problem is related to the use of the wrong registers for passing the values (see this thread https://groups.google.com/forum/#!topic/avian/8nz4JZEPwZs, which was what got me looking at the double value in the first place).

Let me know if there's anything else I can do to help debug.

Jon

Copied from original issue: nativelibs4java/nativelibs4java#525

Struct by value

From @tulskiy on September 1, 2011 5:42

Hi,

I know it is a known limitation that BridJ does not support passing struct by value. I just wanted to leave it here as an issue to be notified in case this feature is ever implemented. Feel free to close the issue if you don't plan on adding it.

Thanks for this great library.

Copied from original issue: nativelibs4java/nativelibs4java#1

Set values for a fixed size array

Hi,

I have a C struct like:

typedef struct type_MyStruct {
    int iMeasure;
    int position[3];
} MyStruct;

When I generate the java class I get something like:

public class MyStruct extends StructObject {
    ...

    @Field(0)
    public int iMeasure() {
        ...
    }

    @Field(0)
    public MyStruct iMeasure(int iMeasure) {
        ...
    }

    @Array({3}) 
    @Field(1) 
    public Pointer<Integer> position() {
        ...
    }

    ...
}

As you can see I don't have a method set for position like:

    @Field(1) 
    public MyStruct position(Pointer<Integer> position) {
        ...
    }

So, how can I set values for this array of 3 positions? For example:

MyStruct myStruct = new MyStruct();
myStruct.iMeasure(10);

???
myStruct.position()

Thanks

Parameterized constructor of C++ is not accessed when used BridJ

From @friends4kunal on May 10, 2012 18:10

Hi
If my Native C++ Code contains class

Class A
{
public :
A( int i, float b, char c)
{ // Constructor }
};

When try to create object of this class A in Java code through BridJ , nothing works, says not able to access default constructor. When used constructor with no parameter everything works perfect. Also when I used BridJ through Plug ins it does not work for CALLBACK , but when I use normal java app and access through main () CALLBACK works perfect

Copied from original issue: nativelibs4java/nativelibs4java#313

C++ Singleton pattern not working

From @slajar on March 28, 2012 17:11

I have a class that is not beeing instanciated by new but by a public static member function.

class API_DECL Test
{
public:
/** the contructor is not available to the public. You'll have to use the singleton patter getInstance() instead. */
static Test * getInstance();

private:
Test();
static Test* instance;
};

Implementation looks like:

Test * Test::instance = NULL;

Test* Test::getInstance()
{
if( Test::instance == NULL )
{
Test::instance = new Test();
}
return Test::instance;
}

...

Unfortunately, jnaerator doesn't generate bridj code to access this static getInstance function.

Ok, so I decided to work around this and generated a C-Function thats called "GetTestInstance()".

ifdef __cplusplus

extern "C"
{

endif

API_DECL Test* GetTestInstance();

ifdef __cplusplus

} //extern "C"

endif

Internally I call Test::getInstance() to return Test pointer.
This compiles successfully. Unfortunately, that doesn't run well. It brings up a Memory error like this:

test = Pointer(peer = 0x5831b08, targetType = com.test.Test)
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2367)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:114)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:587)
at java.lang.StringBuilder.append(StringBuilder.java:214)
at org.bridj.demangling.VC9Demangler.parseNameFragment(VC9Demangler.java:599)
at org.bridj.demangling.VC9Demangler.parseNameQualification(VC9Demangler.java:642)
at org.bridj.demangling.VC9Demangler.parseNameQualifications(VC9Demangler.java:627)
at org.bridj.demangling.VC9Demangler.parseQualifiedTypeName(VC9Demangler.java:428)
at org.bridj.demangling.VC9Demangler.parseType(VC9Demangler.java:364)
at org.bridj.demangling.VC9Demangler.parseType(VC9Demangler.java:352)
at org.bridj.demangling.VC9Demangler.parseFunctionProperty(VC9Demangler.java:117)
at org.bridj.demangling.VC9Demangler.parseSymbol(VC9Demangler.java:215)
at org.bridj.NativeLibrary.parseSymbol(NativeLibrary.java:359)
at org.bridj.demangling.Demangler$Symbol.parse(Demangler.java:306)
at org.bridj.demangling.Demangler$Symbol.matches(Demangler.java:284)
at org.bridj.NativeLibrary.getSymbol(NativeLibrary.java:195)
at org.bridj.cpp.CPPRuntime.registerNativeMethod(CPPRuntime.java:263)
at org.bridj.CRuntime.register(CRuntime.java:357)
at org.bridj.CRuntime.register(CRuntime.java:266)
at org.bridj.CRuntime$CTypeInfo.(CRuntime.java:83)
at org.bridj.cpp.CPPRuntime$CPPTypeInfo.(CPPRuntime.java:704)
at org.bridj.cpp.CPPRuntime.getTypeInfo(CPPRuntime.java:804)
at org.bridj.BridJ.getTypeInfo(BridJ.java:309)
at org.bridj.BridJ.createNativeObjectFromPointer(BridJ.java:206)
at org.bridj.BridJ.createNativeObjectFromPointer(BridJ.java:222)
at org.bridj.Pointer.getNativeObjectAtOffset(Pointer.java:690)
at org.bridj.CommonPointerIOs$NativeObjectPointerIO.get(CommonPointerIOs.java:43)
at org.bridj.CommonPointerIOs$NativeObjectPointerIO.get(CommonPointerIOs.java:11)
at org.bridj.Pointer.get(Pointer.java:831)
at org.bridj.Pointer.get(Pointer.java:800)

How can I solve this issue in a good way that is compliant with Bridj and JNAerator? I can still change the C++ Api to fit any needs.

Copied from original issue: nativelibs4java/nativelibs4java#291

Bridj - JAWTUtils.withLockedSurface slows down

From @sampsonk on August 12, 2012 22:12

I'm trying to run JAWTUtils.withLockedSurface() in a loop to perform rendering. However, even if no rendering is performed, the loop slows down dramatically within the first few seconds until it eventually settles into a specific range.

I'm using Bridj to interface with DirectX 11. When I try to do the above while rendering a single triangle each frame, the JVM eventually crashes (seems to happen after rendering about 10,000 times).

I've included code below to repro the issue along with output. Running on Windows 7 64-bit, Bridj 0.6.1 and 0.6.2-snapshot-20120722, jdk 1.6.0_21

import java.awt.Component;

import javax.swing.JFrame;

import org.bridj.jawt.JAWT;
import org.bridj.jawt.JAWTUtils;
import org.bridj.jawt.JAWTUtils.LockedComponentRunnable;
import org.bridj.jawt.JawtLibrary.JNIEnv;

public class LockedSurfaceTest {
    public static void main(String[] args) {
        JFrame frame = new JFrame("withLockedSurface test");
        frame.setSize(800, 600);
        frame.setIgnoreRepaint(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        JNIEnv env = JAWTUtils.getJNIEnv();
        JAWT jawt = JAWTUtils.getJAWT(env);
        LockedComponentRunnable lcr = new LockedComponentRunnable() {
            @Override
            public void run(Component comp, long peer) {
            }
        };
        int j = 0;
        long startTime = System.currentTimeMillis();
        while(frame.isEnabled()) {

            if(frame.isVisible())
                JAWTUtils.withLockedSurface(env, jawt, frame, lcr);

            j++;
            long endTime = System.currentTimeMillis();
            if(endTime - startTime >= 1000) {
                System.out.println("frames = " + j);
                j = 0;
                startTime = endTime;
            }
        }
    }
}

Output:

frames = 1952
frames = 867
frames = 637
frames = 566
frames = 474
frames = 431
frames = 380
frames = 373
frames = 354
frames = 339
frames = 305
frames = 309
frames = 270
frames = 280
frames = 268
frames = 260
frames = 253
frames = 234
frames = 230
frames = 230
frames = 215
...

Copied from original issue: nativelibs4java/nativelibs4java#332

BridJ: add version-specific package

From @ochafik on April 14, 2012 23:51

As described in issue #272, a version-specific relocated package of BridJ would be nice to have.

The feature is mostly implemented, but some details are missing (namely, the custom native code that does the relocated native method bindings in BridJ/src/main/cpp/bridj/Init.c crashes).

Uncomment shade+relocation package in BridJ/pom.xml and InteropIntegration package in top pom to test.

Copied from original issue: nativelibs4java/nativelibs4java#301

Mac OS X 64 bit broken

From @slajar on April 4, 2012 9:45

I have a universal darwin library that has 32 bit and 64 bit binaries encapsulated. Both work fine in my natve test envioronment. I managed to get the 32 bit running trough jnaerted code (bridj) with "java -d32". Unfortunetely, when I switch over to 64 bit by turning on the "-d64" switch it crashes with the first ".get()" call I do in my sample code.

Copied from original issue: nativelibs4java/nativelibs4java#294

Lack of understanding and strange observation on @Convention

From @ErwinBellon on April 9, 2014 21:32

Please point me to a bit more explanation on @runtime and @convention. I can usually get it to work but do not understand how :-(

When declaring a COM interface, I include a @iid annotation but no further convention or runtime annotation. For a COM object I only provide @iid and @Clsid. I would assume, however, that at least some indication of calling convention were requested. And in some DirectX declarations I detected that both COMRuntime and StdCall were provided.

When declaring Windows API functions resident in a dll, I usually get the stuff working by including @runtime(CPPRuntime.class). But if I also include @convention(StdCall) in the assumption that this refers to the ‘WINAPI’ calling convention, things go wrong.

But for the GetKeyState function in User32.dll I did have to include @convention(StdCall) or the application would crash (at least in a 32 bit JVM; it seemed to work in a 64 bit environment).

Thus, whereas for GetKeyState I HAD TO include the calling convention, I WAS NOT ALLOWED TO do so for a function like RegQueryInfoKeyW in AdvApi32.dll. The former function returns a 16 bit value instead one with 32 bits, but I would assume that this is unrelated.

Many thanks,

Erwin

Copied from original issue: nativelibs4java/nativelibs4java#494

[BridJ] Memory leak in VARIANT even in basic use?

From @ErwinBellon on March 21, 2013 18:28

I am looking for memory leaks in a COM application using an own IMallocSpy implementation (difficult to isolate in a small test application) and suspect VARIANT to leak.

If I track following code:

Pointer pVariant = allocate(VARIANT.class);
pVariant.get().setValue("some string");
pVariant.release();

I get following information about the creation of a memory block that subsequently was never freed:

Memory block at address xxx size16 [size is 16 independent from which string was inserted]
org.bridj.cpp.com.OLEAutomationLibrary.VariantChangeType(Native Method) -2
org.bridj.cpp.com.COMRuntime.change(COMRuntime.java:358) 358
org.bridj.cpp.com.COMRuntime.setValue(COMRuntime.java:389) 389
org.bridj.cpp.com.VARIANT.setValue(VARIANT.java:1119) 1119

I should be using BridJ 6.0.2 on a Windows 7 64 bits OS but in a 32 bit Java environment.

Any hint on how to better use VARIANT was welcome - maybe I should call some other method to properly release the memory. I actually just use VARIANT to get a string from a property bag.

Thanks,

Erwin

Copied from original issue: nativelibs4java/nativelibs4java#389

Android JNI warning with Bridj 0.7

From @kesslerd on February 11, 2014 19:14

Hi ochafik

I'm developing an application for android and use BridJ for native calls.

In Bridj 0.7 I get a JNI warning and the app crashes.

JNI WARNING: instance jfieldID 0x0 not valid for class Lorg/bridj/MethodCallInfo; (GetBooleanField) in Lorg/bridj/JNI;.bindJavaMethodsToCFunctions:([Lorg/bridj/MethodCallInfo;)J (GetBooleanField)

kind regards
kesslerd

Copied from original issue: nativelibs4java/nativelibs4java#474

bound check/GetLastError()

From @smori-tib on January 15, 2013 17:4

I am getting a runtime error when using the jnaerator generated code with BridJ binding from Windows headers. This the snippet from the headers:

define ANYSIZE_ARRAY 1

typedef struct _SID_AND_ATTRIBUTES {
PSID Sid;
DWORD Attributes;
} SID_AND_ATTRIBUTES, * PSID_AND_ATTRIBUTES;

typedef struct _TOKEN_GROUPS {
DWORD GroupCount;
SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY];
} TOKEN_GROUPS, *PTOKEN_GROUPS;

I am allocating the exact number of bytes required by GetTokenInformation() to populate TOKEN_GROUPS. For the purpose of what I am doing, GetTokenInformation populates more than 1 element in TOKEN_GROUPS.Groups attribute. The actual number of elements in Groups is defined by GroupCount and that can only be determined at runtime.
I get this exception when accessing Sid() from TOKEN_GROUPS.Groups[1]:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Cannot access to memory data of length 8 at offset 0 : valid memory start is 229081408, valid memory size is 24
at org.bridj.Pointer.checkPeer(Pointer.java:1094)
at org.bridj.Pointer$OrderedPointer.getLongAtOffset(Pointer.java:300)
at org.bridj.Pointer.getSizeTAtOffset(Pointer.java:3996)
at org.bridj.Pointer.getPointerAtOffset(Pointer.java:3688)
at org.bridj.Pointer.getPointerAtOffset(Pointer.java:3680)
at org.bridj.StructIO.getPointerField(StructIO.java:898)
at test.advapi32.SID_AND_ATTRIBUTES.Sid(SID_AND_ATTRIBUTES.java:20)
...
sizeof(SID_AND_ATTRIBUTES) reports 8 in standalone win32 application.

If I use an arbitrarily large number for ANYSIZE_ARRAY, say 100, I get this exception when accessing TOKEN_GROUPS.Groups():
Exception in thread "main" java.lang.IndexOutOfBoundsException: Cannot extend validity of pointed memory from 234914436 to 234915720
at org.bridj.Pointer.validBytes(Pointer.java:1140)
at org.bridj.Pointer.validElements(Pointer.java:1180)
at org.bridj.StructIO.getPointerField(StructIO.java:896)
at test.advapi32.TOKEN_GROUPS.Groups(TOKEN_GROUPS.java:31)
...

Things work fine when I set ANYARRAY_SIZE to match the exact number of groups.

Any suggestion how to solve this?

Another thing that I observed. I generated GetLastError() also but it seems that the error code are getting swallowed. It always returns 0 even when an error occurred. However, exception is thrown if I add throws LastError in the method signature. Is it possible to get the error code through GetLastError() as opposed to from exception?

Copied from original issue: nativelibs4java/nativelibs4java#361

Source build breaks on pthread4java

From @ilganeli on September 24, 2013 21:53

I am attempting to rebuild to get a bug fix for a pointer issue and have failed when building PThread4Java.

[INFO] Reactor Summary:
[INFO]
[INFO] NativeLibs4Java Common Configuration .............. SUCCESS [3.514s]
[INFO] Interop Integration Root .......................... SUCCESS [0.034s]
[INFO] Maven Velocity Code Generator ..................... SUCCESS [9.307s]
[INFO] BridJ (NativeLibs4Java C/C++ Interop Layer) ....... SUCCESS [26.846s]
[INFO] Anarres JCPP (with JNAerator modifications) ....... SUCCESS [4.900s]
[INFO] JNAerator Parent Project .......................... SUCCESS [0.033s]
[INFO] OChafik's General Utilities ....................... SUCCESS [6.322s]
[INFO] OChafik's Swing Utilities ......................... SUCCESS [7.949s]
[INFO] JNAerator Runtime ................................. SUCCESS [6.174s]
[INFO] JNAerator Rococoa Runtime ......................... SUCCESS [3.108s]
[INFO] JNAerator Parser .................................. SUCCESS [19.223s]
[INFO] JNAerator CLI and Studio Tools .................... SUCCESS [12.317s]
[INFO] JNAerator Maven Plugin ............................ SUCCESS [4.326s]
[INFO] JavaCL Parent Project ............................. SUCCESS [0.043s]
[INFO] LibCL ............................................. SUCCESS [0.371s]
[INFO] OpenCL4Java / BridJ ............................... SUCCESS [3.728s]
[INFO] NativeLibs4Java Common Utilities .................. SUCCESS [3.275s]
[INFO] JavaCL Core / BridJ ............................... SUCCESS [8.865s]
[INFO] JavaCL Generator / BridJ .......................... SUCCESS [3.287s]
[INFO] Maven JavaCL Plugin ............................... SUCCESS [3.194s]
[INFO] JavaCL / BridJ .................................... SUCCESS [6.889s]
[INFO] JavaCL Demos / BridJ .............................. SUCCESS [4.904s]
[INFO] JavaCL Interactive Image Demo / BridJ ............. SUCCESS [4.190s]
[INFO] JavaCL BLAS / BridJ ............................... SUCCESS [11.051s]
[INFO] JavaCL OpenGL Demos / BridJ ....................... SUCCESS [7.863s]
[INFO] JavaCL Tutorial ................................... SUCCESS [4:08.969s]
[INFO] JavaCL Simple Tutorial Archetype .................. SUCCESS [0.312s]
[INFO] JavaCL Tutorials Root / BridJ ..................... SUCCESS [0.034s]
[INFO] PThread4Java ...................................... FAILURE [0.114s]
[INFO] Idle Time Utility Library (BridJ-based & cross-platform) SKIPPED
[INFO] JarShrinker ....................................... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6:53.279s
[INFO] Finished at: Tue Sep 24 17:41:53 EDT 2013
[INFO] Final Memory: 35M/115M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.nativelibs4java:maven-jnaerator-plugin:0.12-SNAPSHOT:generate (default) on project pthread4java:
The parameters 'generateScala' for goal com.nativelibs4java:maven-jnaerator-plugin:0.12-SNAPSHOT:generate are missing or invalid -

[Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginParameterException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR] mvn -rf :pthread4java

Copied from original issue: nativelibs4java/nativelibs4java#448

JNAerator: JNA not working from Weblogic?

From @lagarcia on March 1, 2012 15:57

Hi

Recently I was trying to use JNA/JNAerator in order to invoke methods from a C library within a Java 6 application. I was having some troubles doing the same thing using JNI because an error was raising from a method within the C native library when I executed the Java app.

The thing is that with JNA I was able to skip the error that I was catching when using JNI, but when I included the functionality that was making use of the C native library via JNA within a web application deployed on Weblogic, it didn't seem to work correctly. The native method that seems to fail is loading a file from a file path that is passed as argument. The raising error suggests that the file is not loaded. When using the same function from the standalone app it was working fine, but not from within the web app deployed on Weblogic. The libraries seem to be loaded fine. I didn't try with other app servers.

Do you have any experience or feedback using JNA from web apps?

Thanks and regards,
Luis

Copied from original issue: nativelibs4java/nativelibs4java#277

vector<struct> as returntype: possible? Mapping correct?

From @apiening on September 25, 2012 22:37

Hi bridj users,

after a successful hello world test, I'm running more and more in problems using BridJ in my "real world" app. I wonder if I'm doing something wrong, my type of mapping is not supported or my platform support (Mac OS X, Mountain Lion) is still buggy.

I want to return a container with structs from a C++ function. I used vector but I'm not specifically bound to this container.
I created a simple demo project and a mapping with JNAerator which compiles, but fails with this error:

Exception in thread "main" java.lang.RuntimeException: Invalid return value type !
    at bridjtest_java.bridj.Test.getStruct(Native Method)
    at bridjtest_java.BridJTest_Java.main(BridJTest_Java.java:35)
Java Result: 1

Here is my C++ header that feeds JNAerator:

#include <vector>

struct SimpleStruct {
    int number;
};

class Test {
public:
    Test();
    Test(const Test& orig);
    virtual ~Test();

    std::vector<SimpleStruct> getStruct();
private:

};

This is the mapping I get from JNAerator:

package bridjtest_java.bridj;
import org.bridj.Pointer;
import org.bridj.ann.Library;
import org.bridj.ann.Name;
import org.bridj.cpp.CPPObject;
import org.bridj.cpp.std.vector;

@Library("test")
public class Test extends CPPObject {
    public Test() {
        super();
    }
    /// Original signature : <code>int Test()</code>
    @Name("Test")
    public native int Test$2();
    /// Original signature : <code>int Test(const Test&)</code>
    public native int Test(Pointer<Test > orig);
    /**
     * char* getGaps(const char* outfile);<br>
     * Original signature : <code>std::vector getStruct()</code><br>
     * <i>native declaration : line 50</i>
     */
    public native vector<SimpleStruct> getStruct();
}

And here's the mapping class for the struct:

package bridjtest_java.bridj;
import org.bridj.Pointer;
import org.bridj.StructObject;
import org.bridj.ann.Field;
import org.bridj.ann.Library;

@Library("test")
public class SimpleStruct extends StructObject {
    public SimpleStruct() {
        super();
    }
    @Field(0)
    public int number() {
        return this.io.getIntField(this, 0);
    }
    @Field(0)
    public SimpleStruct number(int number) {
        this.io.setIntField(this, 0, number);
        return this;
    }
    public SimpleStruct(Pointer pointer) {
        super(pointer);
    }
}

Can someone please confirm if this mapping is supported/possible and if it should work or not?
What may cause my error? How can I dig into that?

Thank you very much!

Andreas Piening

Copied from original issue: nativelibs4java/nativelibs4java#341

[BridJ] ITaskbarList3 doesn't work with JavaFX stage

From @AnirvanSarkar on January 27, 2015 10:1

ITaskbarList3 works as expected with JFrame but not with JavaFX stage.

For example, the following Swing code displays a progress in taskbar:

import javax.swing.JFrame;
import org.bridj.Pointer;
import org.bridj.cpp.com.COMRuntime;
import org.bridj.cpp.com.shell.ITaskbarList3;
import org.bridj.jawt.JAWTUtils;

public class SwingTaskbar extends JFrame {

    ITaskbarList3 list;
    Pointer<?> hwnd;

    public SwingTaskbar() throws ClassNotFoundException {

        list = COMRuntime.newInstance(ITaskbarList3.class);

    }

    @Override
    protected void finalize() throws Throwable {

        super.finalize();
        list.Release();

    }

    @Override
    public void setVisible(boolean visible) {

        super.setVisible(visible);

        long hwndVal = JAWTUtils.getNativePeerHandle(this);
        hwnd = Pointer.pointerToAddress(hwndVal);
        list.SetProgressValue((Pointer) hwnd, 50, 100);

    }

    public static void main(String[] args) {

        try {

            SwingTaskbar f = new SwingTaskbar();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setVisible(true);

        } catch (Throwable ex) {

            ex.printStackTrace();

        }

    }

}

But its JavaFX counterpart doesn't show one:

import javafx.application.Application;
import javafx.stage.Stage;
import org.bridj.Pointer;
import org.bridj.cpp.com.COMRuntime;
import org.bridj.cpp.com.shell.ITaskbarList3;

public class FXTaskbar extends Application {

    ITaskbarList3 list;
    Pointer<?> hwnd;

    @Override
    public void init() throws ClassNotFoundException {

        list = COMRuntime.newInstance(ITaskbarList3.class);

    }

    @Override
    public void stop() {
        list.Release();
    }

    @Override
    public void start(Stage primaryStage) {

        primaryStage.show();

        long hwndVal = com.sun.glass.ui.Window.getWindows().get(0).getNativeWindow();
                //com.sun.glass.ui.Window.getFocusedWindow().getNativeHandle();
        hwnd = Pointer.pointerToAddress(hwndVal);
        list.SetProgressValue((Pointer) hwnd, 50, 100);

    }

    public static void main(String[] args) {
        launch(args);
    }

}
OS: Windows 7
Java Version: 1.8.0_31
BridJ Version: bridj-0.7-20141231.010908-73-windows-only

Copied from original issue: nativelibs4java/nativelibs4java#556

Allow getting last error without using the LastError exception

From @skyewire on July 18, 2013 21:21

BridJ needs an API to get the last error (i.e. errno or Windows GetLastError()) without declaring that the native function throws LastError.

The reason for this is that some Windows API functions succeed, but still set the last error. A typical example is CreateMutex: if the mutex already exists, the function succeeds and returns a handle to the mutex (which must be closed) and sets the last error to ERROR_ALREADY_EXISTS. It's not possible to use this function correctly with BridJ at the moment:

  • If your native function throws LastError, then you'll never receive the mutex handle in the ERROR_ALREADY_EXISTS case. This causes a handle leak.
  • If your native function does not throw LastError, then you won't know whether the mutex already existed or not. In some cases, this is vital information.

The last error should be stored in a thread-local variable and be available for the Java code to query until the next native function is called from that thread.

Copied from original issue: nativelibs4java/nativelibs4java#427

BridJ fails to find vtable

From @MHOOO on September 5, 2013 18:3

Given this class definition (with default impl. for the virtual fns):

class BrowserHandler {
public:
    virtual void onPaint();
    virtual size_t width();
    virtual size_t height();
}

and this java class:

package test;
import org.bridj.Pointer;
import org.bridj.ann.Library;
import org.bridj.ann.Ptr;
import org.bridj.ann.Virtual;
import org.bridj.ann.Name;
import org.bridj.cpp.CPPObject;

@Library("test") 
public class BrowserHandler extends CPPObject {
    public BrowserHandler() {
        super();
    }
    @Virtual(0)
    native public void onPaint();

    public static BrowserHandler CreateNew() {
        return new BrowserHandler() {
            @Override
            public void onPaint() {
                System.out.println("test");
            }
        };
    }
}

I get the following error, when invoking BrowserHander.CreateNew():

 [error] Sep 05, 2013 7:52:29 PM org.bridj.BridJ log
[error] INFO: Failed to find a vtable for type class test.BrowserHandler$1

If I do not override the onPaint method, it works as expected. But it would be really nice to be able to override virtual methods.
Any help with this?

I'm using bridj 0.7-SNAPSHOT. The java class is hand-coded, since JNAerator did not produce a running example either.

Copied from original issue: nativelibs4java/nativelibs4java#438

Problem to build BridJ on Raspberry Pi and Cubietruck

From @jo-do on September 29, 2014 17:30

Hello,

I try to rebuild BridJ's native library for Raspberry Pi (Raspian, Linux raspberrypi 3.12.28+ #709 PREEMPT Mon Sep 8 15:28:00 BST 2014 armv6l GNU/Linux, (gnueabihf)) , using the wiki page.
After I applied the BridJ-specific patches (and after CleanNative), I run ./BuildNative and get an error:

[...]
cd dyncallback && make all
make[1]: Entering directory '/home/pi/bridj/nativelibs4java/libraries/BridJ/dyncall/dyncall/dyncallback'
cc -fPIC -I/home/pi/bridj2/nativelibs4java/libraries/BridJ/dyncall/dyncall/././dyncallback/../dyncall    -c -o dyncall_alloc_wx.o dyncall_alloc_wx.c
cc -fPIC -I/home/pi/bridj2/nativelibs4java/libraries/BridJ/dyncall/dyncall/././dyncallback/../dyncall    -c -o dyncall_args.o dyncall_args.c
In file included from dyncall_args.c:36:0:
dyncall_args_arm32_arm_armhf.c: In function ‘arm_float’:
dyncall_args_arm32_arm_armhf.c:62:8: error: ‘DCArgs’ has no member named ‘s’
dyncall_args_arm32_arm_armhf.c:63:22: error: ‘DCArgs’ has no member named ‘S’
dyncall_args_arm32_arm_armhf.c:63:27: error: ‘DCArgs’ has no member named ‘s’
dyncall_args_arm32_arm_armhf.c:64:10: error: ‘DCArgs’ has no member named ‘d’
dyncall_args_arm32_arm_armhf.c:64:17: error: ‘DCArgs’ has no member named ‘s’
dyncall_args_arm32_arm_armhf.c:65:8: error: ‘DCArgs’ has no member named ‘d’
dyncall_args_arm32_arm_armhf.c:65:16: error: ‘DCArgs’ has no member named ‘s’
dyncall_args_arm32_arm_armhf.c:67:8: error: ‘DCArgs’ has no member named ‘s’
dyncall_args_arm32_arm_armhf.c:67:15: error: ‘DCArgs’ has no member named ‘d’
dyncall_args_arm32_arm_armhf.c: In function ‘arm_double’:
dyncall_args_arm32_arm_armhf.c:77:8: error: ‘DCArgs’ has no member named ‘d’
dyncall_args_arm32_arm_armhf.c:79:36: error: ‘DCArgs’ has no member named ‘S’
dyncall_args_arm32_arm_armhf.c:79:41: error: ‘DCArgs’ has no member named ‘d’
dyncall_args_arm32_arm_armhf.c:80:6: error: ‘DCArgs’ has no member named ‘d’
dyncall_args_arm32_arm_armhf.c:81:12: error: ‘DCArgs’ has no member named ‘s’
dyncall_args_arm32_arm_armhf.c:85:8: error: ‘DCArgs’ has no member named ‘s’
dyncall_args_arm32_arm_armhf.c:85:15: error: ‘DCArgs’ has no member named ‘d’
dyncall_args_arm32_arm_armhf.c:89:6: error: ‘DCArgs’ has no member named ‘s’
<builtin>: recipe for target 'dyncall_args.o' failed
make[1]: *** [dyncall_args.o] Error 1
make[1]: Leaving directory '/home/pi/bridj2/nativelibs4java/libraries/BridJ/dyncall/dyncall/dyncallback'
/home/pi/bridj2/nativelibs4java/libraries/BridJ/dyncall/dyncall/././Makefile.generic:7: recipe for target 'libdyncallback' failed
make: *** [libdyncallback] Error 2
Failed building dyncall

(With git revision 79b7deb612f7bd9b1602a48d917fdd5df9920bec)

It seems that the wrong header in dyncall.diff, line 141, is included. After replacing +#include "dyncall_args_arm32_arm.h" with +#include "dyncall_args_arm32_arm_armhf.h" everything goes fine. (Or, alternatively, alter the header include in dyncallback/dyncall_args_arm32_arm_armhf.c after patching.)

mvn clean install -DskipTests ends with Build success.

However, when I test it via mvn test, I get many many errors and failures, especially segmentation faults! I append the output of mvn -X test, see file test_result_only_bridj_native_build.txt.
If I build BridJ only (but not the native library) the test result is far better: No segmentation faults, but the Java Virtual Machine often crashes (please see again the output of this test run, file test_result_only_bridj_no_native.txt.)

I tried all this with java openjdk-6 version "1.6.0_32".

Does anybode have an idea what the problem is? Is there anything that I have to do in addition to build Bridj? (I.e. install software.) @ochafik Would it be possible that you update the binaries for Linux armv6l, maybe its getting better with your dyncall_callback_arm32_arm_armhf included?

I did the same procedure on the Cubietruck (Linux Cubian 3.4.75-sun7i #36 SMP PREEMPT Mon Feb 10 02:47:28 CST 2014 armv7l GNU/Linux, Processor: ARMv7 Processor rev 4 (v7l), Features: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt, (also gnueabihf)). Patching and building the BridJ native libraries goes without errors, because dyncall/dyncallback/dyncall_args.c includes dyncall_args_arm32_thumb.c instead of dyncall_args_arm32_arm_armhf.c. But rebuilding BridJ's native library and BridJ leads basically to the same errors as above, except that in the raspberry pi case I get some kind of benchmark output in addition:

[...]
# Fields read/write :
# Optimal took 135015.559074 millis to read/write 1000000 simple structs : 135.015559074 microsecond per struct
# BridJ took 29599.200284 millis to read/write 1000000 simple structs : 29.599200284000002 microsecond per struct
[...]

Best regards, thank you in advance for your help!

Jonas

Copied from original issue: nativelibs4java/nativelibs4java#531

Source build breaks on BridJ

From @AODtorusan on February 25, 2014 20:9

Hi,

Building the nativelibs4java libraries from the source repository crashes on the BridJ sub-project:

> mvn clean install
...
Failed tests: 
  DemanglingTest.testLongLongBackReference:94->demangle:449->checkSymbol:487 Bad type for 1th param : (symbol = null test_add9_long(CLong, CLong, CLong, CLong, CLong, CLong, CLong, CLong, CLong), expecting long and demangled CLong (org.bridj.demangling.Demangler$JavaTypeRef)
   Expected exception: org.bridj.LastError
  STLTest.testList:111 null

Tests in error: 
  NamespacesTest.testSimplyNamespaced:188 ۠UnsatisfiedLink org.bridj.Namespaces...
  NamespacesTest.testFullyNamespaced:200 ۠UnsatisfiedLink org.bridj.NamespacesT...
  NamespacesTest.testTopLevelClass:194 ۠UnsatisfiedLink org.bridj.NamespacesTes...

Tests run: 444, Failures: 3, Errors: 3, Skipped: 4

[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO] 
[INFO] NativeLibs4Java Common Configuration .............. SUCCESS [1.721s]
[INFO] Interop Integration Root .......................... SUCCESS [0.045s]
[INFO] Maven Velocity Code Generator ..................... SUCCESS [11.182s]
[INFO] BridJ (NativeLibs4Java C/C++ Interop Layer) ....... FAILURE [4:07.522s]
[INFO] Anarres JCPP (with JNAerator modifications) ....... SKIPPED
...
[INFO] JarShrinker ....................................... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

The error for DemanglingTest:

Test set: org.bridj.DemanglingTest
Tests run: 31, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.385 sec <<< FAILURE!
testLongLongBackReference(org.bridj.DemanglingTest)  Time elapsed: 0.196 sec  <<< FAILURE!
java.lang.AssertionError: Bad type for 1th param : (symbol = null test_add9_long(CLong, CLong, CLong, CLong, CLong, CLong, CLong, CLong, CLong), expecting long and demangled CLong (org.bridj.demangling.Demangler$JavaTypeRef)
    at org.junit.Assert.fail(Assert.java:93)
    at org.junit.Assert.assertTrue(Assert.java:43)
    at org.bridj.DemanglingTest.checkSymbol(DemanglingTest.java:487)
    at org.bridj.DemanglingTest.demangle(DemanglingTest.java:449)
    at org.bridj.DemanglingTest.testLongLongBackReference(DemanglingTest.java:94)

The error for STLTest:

Test set: org.bridj.STLTest
Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.59 sec <<< FAILURE!
testList(org.bridj.STLTest)  Time elapsed: 0.093 sec  <<< FAILURE!
java.lang.AssertionError: null
    at org.junit.Assert.fail(Assert.java:92)
    at org.junit.Assert.assertTrue(Assert.java:43)
    at org.junit.Assert.assertNull(Assert.java:551)
    at org.junit.Assert.assertNull(Assert.java:562)
    at org.bridj.STLTest.testList(STLTest.java:111)

The error for NamespacesTest:

Test set: org.bridj.NamespacesTest
Tests run: 3, Failures: 0, Errors: 3, Skipped: 0, Time elapsed: 0.767 sec <<< FAILURE!
testSimplyNamespaced(org.bridj.NamespacesTest)  Time elapsed: 0.177 sec  <<< ERROR!
java.lang.UnsatisfiedLinkError: org.bridj.NamespacesTest$RenamedSimplyNamespacedClass.renamedGetValue()I
    at org.bridj.NamespacesTest$RenamedSimplyNamespacedClass.renamedGetValue(Native Method)
    at org.bridj.NamespacesTest.testSimplyNamespaced(NamespacesTest.java:188)

testFullyNamespaced(org.bridj.NamespacesTest)  Time elapsed: 0.011 sec  <<< ERROR!
java.lang.UnsatisfiedLinkError: org.bridj.NamespacesTest$FullyNamespacedClass.renamedGetValue()I
    at org.bridj.NamespacesTest$FullyNamespacedClass.renamedGetValue(Native Method)
    at org.bridj.NamespacesTest.testFullyNamespaced(NamespacesTest.java:200)

testTopLevelClass(org.bridj.NamespacesTest)  Time elapsed: 0.02 sec  <<< ERROR!
java.lang.UnsatisfiedLinkError: org.bridj.NamespacesTest$TopLevelClass.renamedGetValue()I
    at org.bridj.NamespacesTest$TopLevelClass.renamedGetValue(Native Method)
    at org.bridj.NamespacesTest.testTopLevelClass(NamespacesTest.java:194)

This happens at revision cfee2748 under the following jvm:

Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 14:51:28+0100)
Maven home: C:\Program Files (x86)\apache-maven-3.0.5
Java version: 1.7.0_17, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.7.0_17\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 8", version: "6.2", arch: "amd64", family: "windows"

I've also updated the full command line output and test logs to http://static.angelcorp.be/stuff/bridj/

Copied from original issue: nativelibs4java/nativelibs4java#477

BridJ 0.7-SNAPSHOT gives segmentation error on IBM JRE

From @AndreasSandberg on June 10, 2014 17:1

When trying to upgrade my BridJ libraries from 0.6.2 to the latest 0.7 snapshot I run into a segmentation fault using a IBM JRE. I have already used the 0.7 version on the same OS (Linux) running a Oracle JRE with success. I've tried to analyse the core dump and here are my findings so far:

The error is of type Segmentation error:

Unhandled exception
Type=Segmentation error vmState=0x00000000
J9Generic_Signal_Number=00000004 Signal_Number=0000000b Error_Value=00000000 Signal_Code=00000001
Handler1=00007FCCF33C29A0 Handler2=00007FCCF3061BD0 InaccessibleAddress=0000000000000010
...
/libj9vm26.so
Module_base_address=00007FCCF33A7000
Target=2_60_20140409_195732 (Linux 2.6.32-220.13.1.el6.x86_64)
CPU=amd64 (2 logical CPUs) (0xef927000 RAM)
Stack Backtrace
(0x00007FCCF33DE24C [libj9vm26.so+0x3724c])

And the corresponding core txt file gives me;
1XMCURTHDINFO Current thread
3XMTHREADINFO "main" J9VMThread:0x00000000224B0100, j9thread_t:0x00007FCCEC007BE0, java/lang/Thread:0x00000000025D9CF8, state:R, prio=5
3XMJAVALTHREAD (java/lang/Thread getId:0x1, isDaemon:false)
3XMTHREADINFO1 (native thread ID:0x7515, native priority:0x5, native policy:UNKNOWN)
3XMTHREADINFO2 (native stack address range from:0x00007FCCF3775000, to:0x00007FCCF4176000, size:0xA01000)
3XMCPUTIME CPU usage total: 1.623299182 secs
3XMHEAPALLOC Heap bytes allocated since last GC cycle=718152 (0xAF548)
3XMTHREADINFO3 Java callstack:
4XESTACKTRACE at org/bridj/JNI.bindJavaMethodsToCFunctions(Native Method)
4XESTACKTRACE at org/bridj/NativeEntities.addDefinitions(NativeEntities.java:149)
4XESTACKTRACE at org/bridj/CRuntime.register(CRuntime.java:468)
5XESTACKTRACE (entered lock: org/bridj/CRuntime@0x0000000002557DE0, entry count: 1)
4XESTACKTRACE at org/bridj/CRuntime.register(CRuntime.java:345)
4XESTACKTRACE at org/bridj/BridJ.register(BridJ.java:363)
4XESTACKTRACE at org/bridj/BridJ.register(BridJ.java:203)
5XESTACKTRACE (entered lock: org/bridj/BridJ@0x00000000024CB1E8, entry count: 1)
4XESTACKTRACE at .../jna/TbusLibrary.(TbusLibrary.java:28)
4XESTACKTRACE at java/lang/J9VMInternals.initializeImpl(Native Method)
4XESTACKTRACE at java/lang/J9VMInternals.initialize(J9VMInternals.java:237(Compiled Code))

The IBM snap file indicates that the class org/bridj/CallIO is loaded before the error handling is invoked;

14:25:40.271491000 0x224b0100 j9vm.221 Event sendInitialize - class org/bridj/CallIO
14:25:40.271493000 0x224b0100 j9bcverify.107 Entry >j9bcv_verifyBytecodes - org/bridj/CallIO
14:25:40.271495000 0x224b0100 j9bcverify.50 Entry >checkAllClassLoadingConstraints(ramClass=0x2270d500 -- org/bridj/CallIO)
14:25:40.271496000 0x224b0100 j9bcverify.111 Exit <j9bcv_verifyBytecodes - returning 0
14:25:40.271502000 0x224b0100 j9vm.20 Entry >sendClinit
14:25:40.271503000 0x224b0100 j9vm.21 Exit <sendClinit (no found)
14:25:40.271504000 0x224b0100 j9vm.315 Entry >0X224b0100 loader 0x7fccec042ba8 class org/bridj/LastError arbitratedLoadClass enter className
14:25:40.271508000 0x224b0100 j9vm.119 Event send loadClass(org/bridj/LastError), stringObject: 0x2238d1b0 loader: 0x25d64e8
14:25:40.271509000 0x224b0100 j9vm.28 Entry >sendLoadClass
14:25:40.271519000 0x224b0100 j9vm.351 Entry >loader 0x25d5f00 class org/bridj/LastError attemptDynamicClassLoad entry
14:25:40.271528000 0x224b0100 j9vm.353 Exit <loader 0x0 class 0X7fccf41737e0 attemptDynamicClassLoad exit
14:25:40.271833000 0x224b0100 j9bcverify.14 Entry >j9bcv_verifyClassStructure - class: org/bridj/LastError
14:25:40.271849000 0x224b0100 j9bcverify.18 Exit <j9bcv_verifyClassStructure
14:25:40.271934000 0x224b0100 j9vm.1 Entry >Create RAM class from ROM class 0x7fccec73e8d8 in class loader 0x7fccec042ba8
14:25:40.271936000 0x224b0100 j9vm.80 Event ROM class 0x7fccec73e8d8 is named org/bridj/LastError

I'm not sure how to analyse this error further, I could probably add some debug logging but so far I haven't seen anything useful in my application logs.

Copied from original issue: nativelibs4java/nativelibs4java#514

Executable stack warning from JVM

From @shevek on December 16, 2014 3:8

OpenJDK 64-Bit Server VM warning: You have loaded library /tmp/BridJExtractedLibraries8475793964869801810/libbridj.so which might have disabled stack guard. The VM will try to fix the stack guard now.

I don't think I invoked BridJ. I got this from the gradle-jnaerator-plugin test suite. Why did it load a library I didn't execute?

Copied from original issue: nativelibs4java/nativelibs4java#541

JVM Crash on BridJ.register (windows x64 / vc11)

From @AODtorusan on January 10, 2014 18:57

Hi,

I am trying to use Bridj to interface to the novas C library.

I've created the dynamic libraries for both linux (gcc 4.8.1) and windows (Visual Studio 2012). However when I try to use the bindings in a basic Java program, the Windows version crashes the JVM:

...
INFO: Property gnu.classpath.boot.library.path = null
jan 10, 2014 7:28:33 PM org.bridj.BridJ log
INFO: Loaded library 'novasj' from 'C:\Users\simon\AppData\Local\Temp\BridJExtractedLibraries3452243142746831809\novasj.dll'
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006a92c880, pid=93624, tid=95028
#
# JRE version: OpenJDK Runtime Environment (7.0-b24) (build 1.7.0-u6-unofficial-b24)
# Java VM: OpenJDK 64-Bit Server VM (24.0-b52 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# V  [jvm.dll+0x20c880]  UTF8::unicode_length+0x0
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:\Users\simon\workspace\novas\novasjTest\hs_err_pid93624.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.sun.com/bugreport/crash.jsp
#

The Linux build does not crash and produces the correct output. I am running in the following environments:

OS name: "windows 8", version: "6.2", arch: "amd64", family: "windows", Java version: 1.7.0_17, vendor: Oracle Corporation
OS name: "linux", version: "3.11.0-12-generic", arch: "amd64", family: "unix", Java version: 1.7.0_25, vendor: Oracle Corporation

Do you have any idea what caused this crash?

And am using the latest BridJ artifact (com.nativelibs4java:bridj:0.7-SNAPSHOT). The full output of the application, the JVM error report file together with the sources and artifacts of my project are located at http://static.angelcorp.be/projects/novas/ .

Simon Billemont

Copied from original issue: nativelibs4java/nativelibs4java#471

Dll Demangle error in UnsatisfiedLinkError

From @xinjian0394 on January 30, 2015 3:35

Hi,
I'm trying BridJ in win7 with JDK 1.7 32b vs08sp1 , and some UnsatisfiedLinkError occurred.
I thought this would be some bug while demangling DLL symbol.

here is some debug message example that i think would help:

symbol="?paramtesta@Mytest@mydlltest@@QAEXHPADMPAVMyClass@2@@z",
demangled="void mydlltest.Mytest.paramtesta(int, byte_, float, 2.MyClass_)"
void paramtesta(int a, char* dtr, float f, MyClass* tmp);

symbol="?paramtestb@Mytest@mydlltest@@QAEXHPAVMyClass@2@PADM@Z",
demangled="null ?paramtestb@Mytest@mydlltest@@QAEXHPAVMyClass@2@PADM@Z()"
void paramtestb(int a, MyClass* tmp, char* dtr, float f);

symbol="?paramstesta@Mytest@mydlltest@@QAEXHPADMPAVMyClass@2@1@Z",
demangled="null ?paramstesta@Mytest@mydlltest@@QAEXHPADMPAVMyClass@2@1@Z()"
void paramstesta(int a, char* dtr, float f, MyClass* tmp1, MyClass* tmp2);

symbol="?paramstestb@Mytest@mydlltest@@QAEXHPADPAVMyClass@2@M1@Z",
demangled="null ?paramstestb@Mytest@mydlltest@@QAEXHPADPAVMyClass@2@M1@Z()"
void paramstestb(int a, char* dtr, MyClass* tmp1, float f, MyClass* tmp2);

symbol="?paramstest2b@Mytest@mydlltest@@QAEXHPADPAVMyClass@2@MAAV32@@z",
demangled="void mydlltest.Mytest.paramstest2b(int, byte_, MAAV32.2.MyClass_)"
void paramstest2b(int a, char* dtr, MyClass* tmp1, float f, MyClass& tmp2);

symbol="?paramstest3b@Mytest@mydlltest@@QAEXHPADAAVMyClass@2@MPAV32@@z",
demangled="void mydlltest.Mytest.paramstest3b(int, byte_, MPAV32.2.MyClass&)"
void paramstest3b(int a, char_ dtr, MyClass& tmp1, float f, MyClass* tmp2);

Please let me know if more info is needed.
Thanks a lot.

Copied from original issue: nativelibs4java/nativelibs4java#558

BridJ: COM deadlock on application exit: CoUninitialize() called from wrong thread?

From @ochafik on September 1, 2011 18:34

First, have you checked out the FAQ
(http://code.google.com/p/nativelibs4java/wiki/FAQ) and Build instructions
(http://code.google.com/p/javacl/wiki/Build) ?
Yes.

Have you looked at NativeLibs4Java's user group's archive ?
(http://groups.google.com/group/nativelibs4java)
Yes.

What steps will reproduce the problem?

  1. Create any COM object on Windows XP.
  2. Call Release() on it or not, it doesn't matter.
  3. Let control leave your public static void main().

What is the expected output? What do you see instead?
It is expected that the application will exit when it leaves main(). It doesn't exit. Attempting to stack trace it with jstack causes jstack to also lock up without giving any output.

What version of the product are you using? On what operating system?
JDK 1.6.0_26 on Windows XP.

If the JVM crashes, please attach the hs_err_pidXXX.log crash report file
written by the JVM.
It doesn't crash.

Please provide any additional information below.
When I install Java in Wine, and run the code with the +ole debug channel in that setup, I see that CoUninitialize() is called from the wrong thread. I think this is because the finalizer thread calls the finalize() method of COMRuntime's comInitializer object, which is not the thread that called CoInitializeEx(). I tried to patch COMRuntime to expose CoInitializeEx and CoUninitialize() in its public API and not use the comInitializer object, and calling these methods manually in the same thread fixes the problem. The patch is attached, but sadly this is an API breaking change.

Google Code Info:
Issue #: 75
Author: [email protected]
Created On: 2011-07-04T05:21:26.000Z
Closed On:

Copied from original issue: nativelibs4java/nativelibs4java#77

Javadoc problems

From @kazocsaba on June 28, 2012 13:13

Some issues with the Javadoc that I stumbled upon without looking explicitly.

Pointer.validElements(): mentions "valid bytes" at one place.
Pointer.getFloatBuffer() and Pointer.getFloatBuffer(long length): mention byte offset
CLContext.createFloatBuffer(Usage kind, Pointer data): talk about the copy parameter that this overload doesn't have

Copied from original issue: nativelibs4java/nativelibs4java#323

BridJ 0.6 regression compared to 0.6-SNAPSHOT

From @trandi on November 14, 2011 16:49

As per the discussion here:
http://groups.google.com/group/nativelibs4java/browse_thread/thread/5baf2df02ad5425f?pli=1

There seem to have been a regression in the way the 0.6 version handles the loading of the library.

Here's the verbose output obtained with BRIDJ_VERY_VERBOSE=1.

As already mentioned, the EXACT same configuration / code works with 0.6-SNAPSHOT (from the 24th of Oct) but if I replace the bridj jar with the 0.6 version (and this is the ONLY change), THEN I get this error :


T E S T S

Running com.markit.quic.dispatchapi.PRDCTest
14-Nov-2011 14:42:20 org.bridj.BridJ log
INFO: Embedded paths for library bridj : [org/bridj/lib/win64/
bridj.dll, lib/win64/bridj.dll]
14-Nov-2011 14:42:20 org.bridj.BridJ log
INFO: Loading library C:\Users\DAN\AppData\Local\Temp
\bridj.dll6524064044671421676.dll
14-Nov-2011 14:42:20 org.bridj.BridJ log
INFO: Loaded library C:\Users\DAN\AppData\Local\Temp
\bridj.dll6524064044671421676.dll
14-Nov-2011 14:42:20 org.bridj.BridJ log
INFO: Runtime for com.markit.quic.dispatchapi.QuicLib :
org.bridj.CRuntime
14-Nov-2011 14:42:20 org.bridj.AbstractBridJRuntime log
INFO: Registering type com.markit.quic.dispatchapi.QuicLib
14-Nov-2011 14:42:20 org.bridj.BridJ log
INFO: Looking for library 'QuicDispatchCpp' in paths [D:/Program Files/
quic/quic/quic-platform/v3.10/bin, null, .,........ D:\Program Files
\groovy-1.8.0\bin, D:\Program Files\maven\bin, D:\Program Files\apache-
ant-1.8.1\bin, D:\cygwin\bin, D:\Program Files, D:\Program Files
\Fortify 360 v2.6.5\bin, D:\Program Files\fortifyclient\bin, C:
\progsDan\apache-ant-1.8.1\bin, D:\Program Files\Java\jdk1.6.0_25\jre
\bin]
14-Nov-2011 14:42:20 org.bridj.AbstractBridJRuntime log
SEVERE: Method public static native
org.bridj.Pointer<com.markit.quic.dispatchapi.bridj.IQuicDispatch>
com.markit.quic.dispatchapi.QuicLib.QuicCreateDispatch() cannot be
mapped : java.lang.RuntimeException: Library 'QuicDispatchCpp' was not
loaded successfully from file 'D:\Program Files\quic\quic\quic-platform
\v3.10\bin\QuicDispatchCpp.dll'
java.lang.RuntimeException: Library 'QuicDispatchCpp' was not loaded
successfully from file 'D:\Program Files\quic\quic\quic-platform
\v3.10\bin\QuicDispatchCpp.dll'
at org.bridj.BridJ.getNativeLibrary(BridJ.java:854)
at org.bridj.BridJ.getNativeLibrary(BridJ.java:833)
at org.bridj.BridJ.getNativeLibrary(BridJ.java:451)
at org.bridj.CRuntime.register(CRuntime.java:333)
at org.bridj.CRuntime.register(CRuntime.java:246)
at org.bridj.BridJ.register(BridJ.java:286)
at org.bridj.BridJ.register(BridJ.java:155)
at com.markit.quic.dispatchapi.QuicLib.(QuicLib.java:
35)
at com.markit.quic.dispatchapi.Quic.(Quic.java:25)
at com.markit.quic.dispatchapi.PRDCTest.test(PRDCTest.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:
39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImp l.java:
25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod
$1.runReflectiveCall(FrameworkMethod.java:45)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable. java:
15)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.j ava:
42)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.ja va:
20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:
263)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.ja va:
68)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.ja va:
47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:
60)
at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:
50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:
222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at
org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:
62)
at
org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(A bstractDirectoryTestSuite.java:
140)
at
org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(Abstract DirectoryTestSuite.java:
127)
at org.apache.maven.surefire.Surefire.run(Surefire.java:177)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:
39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImp l.java:
25)
at java.lang.reflect.Method.invoke(Method.java:597)
at
org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(Surefire Booter.java:
345)
at
org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:
1009)
14-Nov-2011 14:42:20 org.bridj.AbstractBridJRuntime log

Here is the Java class also :

@Library("QuicDispatchCpp")
class QuicLib {
private static final Logger log = Logger.getLogger(QuicLib.class);

// Must point to the directory where QuicDispatchCpp.dll lives.
// Alternatively the system will search for the .dll on the path
public static final String QUIC_LIB_PATH_PROP = "quic.library.path";

private static QuicLib instance;

static {
    final String quicLibPath = System.getProperty(QUIC_LIB_PATH_PROP);
    if(quicLibPath != null && !"".equals(quicLibPath)) {
        BridJ.addLibraryPath(quicLibPath);
    }else{
        log.warn("Property " + QuicLib.QUIC_LIB_PATH_PROP + " has NOT been set. \n" +
                "It's likely we won't find the required QuicDispatchCpp.dll, unless it's on the class path ! \n" +
                "If you see a UnsatisfiedLinkError, you'll know why ! :)");
    }

    BridJ.register();
}



native public static Pointer<IQuicDispatch> QuicCreateDispatch();
native void QuicReleaseDispatch(Pointer<IQuicDispatch> piDispatch);


native Pointer<IDispatchVariant> QuicCreateDispatchVariant();
native void QuicReleaseDispatchVariant(Pointer<IDispatchVariant> piVariant);
native void QuicLiberateDispatchVariant(Pointer<IDispatchVariant> piVariant);


/**
 * Singleton factory method
 * @return The only and staticly unique instance of the library.
 */
public static QuicLib instance(){
    if(instance == null){
        instance = new QuicLib();
    }

    return instance;
}

}

I get the error when doing QuicLib.QuicCreateDispatch();

Thanks,
dan

Copied from original issue: nativelibs4java/nativelibs4java#201

Bridj sum two int return wrong

From @i2534 on September 22, 2014 8:19

I write a simple c++ code for test,like this:

ifndef HELLO_H

define HELLO_H

define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

class Hello
{
public:
Hello(const int& a, const int& b);
~Hello();

int Sum();

private:
int a;
int b;
};

EXTERN_DLL_EXPORT Hello* NewHello(int a, int b);
EXTERN_DLL_EXPORT int Sum(Hello* h);

endif // HELLO_H

on windows 8,use qtcreator export to dll
then java code:

public interface JNAHelloLib extends StdCallLibrary {

    JNAHelloLib INSTANCE = (JNAHelloLib) Native.loadLibrary("hello",
            JNAHelloLib.class);

    com.sun.jna.Pointer NewHello(int a, int b);

    int Sum(com.sun.jna.Pointer p);
}

@Library("hello")
public static class Hello extends CPPObject {
    static {
        BridJ.register();
    }

    /** Original signature : <code>Hello(const int&, const int&)</code> */
    @Constructor(0)
    public Hello(Pointer<Integer> a, Pointer<Integer> b) {
        super((Void) null, 0, a, b);
    }

    /**
     * Original signature : <code>int Sum()</code><br>
     * <i>native declaration : line 13</i>
     */
    public native int Sum();

    @Field(0)
    public int a() {
        return this.io.getIntField(this, 0);
    }

    @Field(0)
    public Hello a(int a) {
        this.io.setIntField(this, 0, a);
        return this;
    }

    @Field(1)
    public int b() {
        return this.io.getIntField(this, 1);
    }

    @Field(1)
    public Hello b(int b) {
        this.io.setIntField(this, 1, b);
        return this;
    }
}

/**
 * @param args
 */
public static void main(String[] args) {
    JNAHelloLib h = JNAHelloLib.INSTANCE;
    System.out.println(h.Sum(h.NewHello(1, 2)));

    Pointer<Integer> a = Pointer.allocateInt();
    a.set(5);
    Pointer<Integer> b = Pointer.allocateInt();
    b.set(10);
    Hello h1 = new Hello(a, b);
    // h1.a(5);
    // h1.b(10);
    System.out.println(h1.a());
    System.out.println(h1.b());
    System.out.println(h1.Sum());
}

output is :
3
0
0
1840125516

what happend?

Copied from original issue: nativelibs4java/nativelibs4java#530

IOException when loading a native library inside an OSGI bundle using jna.library.path

From @ochafik on September 1, 2011 18:47

What steps will reproduce the problem?

  1. Create an OSGi bundle that uses a jnaerated CustomLibrary.INSTANCE
  2. Run OSGi container with path to native library (-Djna.library.path=lib)
  3. Deploy and start the custom bundle

What is the expected output? What do you see instead?
The JNAerated code should run without problem as according to the documentation jna.library.path is where libraries are looked for at run-time. Instead an IOException is thrown by the call LibraryExtractor.getLibraryPath()

What version of the product are you using? On what operating system?
maven-jnaerator-plugin 0.9.5 on Windows 7

Is the problem still present in the latest SVN version ?
Yes

Workaround:
Instead of defining jna.library.path, set library.custom
-Dlibrary.custom=lib\custom.dll
This tricks LibraryExtractor.getLibraryPath()

Stack trace of the Exception:
ERROR: Failed to extract library mOcrApi
java.io.IOException: Cannot list contents of bundle://5.0:1/libraries/win32
at com.ochafik.net.URLUtils.listFiles(URLUtils.java:58)
at com.ochafik.lang.jnaerator.runtime.LibraryExtractor.getLibraryPath(Li
braryExtractor.java:96)
at xx.CustomLibrary.(CustomLibrary.jav
a:18)
at xx.CustomDriver.(CustomDriver.java
:16)
at xx.CustomBundleActivator.start(CustomBundleActivator
eActivator.java:12)
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAct
ion.java:633)
at org.apache.felix.framework.Felix.activateBundle(Felix.java:1822)
at org.apache.felix.framework.Felix.startBundle(Felix.java:1739)
at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1143)

    at org.apache.felix.framework.StartLevelImpl.run(StartLevelImpl.java:264

)
at java.lang.Thread.run(Unknown Source)

Google Code Info:
Issue #: 76
Author: [email protected]
Created On: 2010-11-30T15:21:38.000Z
Closed On:

Copied from original issue: nativelibs4java/nativelibs4java#153

Bridj 0.6 won't work on java 5

From @aaime on January 15, 2012 17:55

While the library is compiled with Java 5 binary compatibility it won't work because it uses Java 6 only API.

So far I've noticed this one:

java.lang.NoSuchMethodError: java.util.Properties.stringPropertyNames()Ljava/util/Set;

but there might be others. In GeoTools 2.7.x series we also have to respect Java 5 compliance and have found that pretty much the only way to avoid these problems is to either use a JDK 1.5 locally to build the project or have continuous build that uses Java 1.5 to double check the project actually works there.

Copied from original issue: nativelibs4java/nativelibs4java#237

Can't load bridj in Android Env.

From @wpoosanguansit on July 10, 2014 16:45

Hi,

I tried to use the library in Android but I get this error while try calling the addTwoInts method:

07-10 12:22:05.922 9413-9413/test W/System.err﹕ java.lang.RuntimeException: Failed to initialize BridJ (java.lang.UnsatisfiedLinkError: Couldn't load bridj from loader dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/test-2.apk"],nativeLibraryDirectories=[/data/app-lib/test-2, /vendor/lib, /system/lib]]]: findLibrary returned null)

I have used both 0.7 snapshot and 0.63. The code compiles correctly but throws up the run time exception as above. Is there any setup needed other than including it in the libs? Thanks for your help.

Copied from original issue: nativelibs4java/nativelibs4java#520

VTable Alignment Issue

From @asherkin on June 13, 2012 16:37

BridJ appears to automatically handle the "extra" virtual dtor that GCC adds into the vtable (which in most cases would give you seamless comparability).

However, in the case of abstract classes, this is not present, causing the function indices to be miss-aligned when calling.

While I haven't tested (and therefore really shouldn't mention it, but, shhh :P), I'm guessing this'll also be a problem with how MSVC and GCC order overloaded functions (and even weirder, overloads from inherited classes) differently as well.

Copied from original issue: nativelibs4java/nativelibs4java#318

Getting Linux JVM stack guard disabled issue

From @Urge2Learn on June 2, 2014 10:22

Getting Linux JVM stack guard disabled issue. Referred #468, and tried all the approaches, still no improvement. Using 0.7-SNAPSHOT. Even if the generated .so is of 64 bit version from a native code that has a deprecated method. Changing the native code to replace the deprecated method also gives same error. Pls help..

Copied from original issue: nativelibs4java/nativelibs4java#510

Passing structures "by value"

From @ivangfr on January 19, 2015 14:41

Hi,

I have a function with this signature:

int DeleteElement(FOO*, BAR, char, char);

However, when I execute it, I get a RuntimeException error: "Failed to get low-level struct representation !"

I implemented a second version of the function, now the second parameter is a pointer:

int DeleteElement2(FOO*, BAR*, char, char);

Now it works.

Googling about it, I found this (https://groups.google.com/forum/#!topic/nativelibs4java/Xj4Y-yTB8DI) when you said that

"Unfortunately passing and returning structures "by value" (as opposed to "by reference" or "by pointer") is not supported by BridJ yet (the underlying dyncall library doesn't support them).
It's currently my top priority for BridJ". (1/9/13)

So, I would like to confirm if it's not implemented in the version 0.6.2? Do you plan to implement it in the next versions?

Congratulations! It's a great project!

Regards

Copied from original issue: nativelibs4java/nativelibs4java#554

vtable not found

From @alexrabo on March 12, 2012 21:2

Upon running jnaerator with mydll and a header, I am getting following error

"SEVERE: Failed to find a vtable for type mylib.ClassName" I am using jnaerator-0.9.10.jar. From command line I entered
java -jar janerator-0.9.10.jar -arch win32 -library MyLib MyLib.h MyLib.dll. The Class I am trying to instantiate is a pure virtual C++. If it was C++, I would be creating a derived class and implementing all method calls. I pretty sure this Class is inside MyLib.dll. Why can I not see vtable of functions for this class?

Copied from original issue: nativelibs4java/nativelibs4java#287

Structures with generic fields not working

BridJ cannot properly handle structs with nested generic types. For instance, the following test case will not work:

package org.bridj;

import org.bridj.ann.Field;
import org.junit.Test;

public class GenericStructTest {
  // a structure to nest.
  public static class Nested extends StructObject {
    @Field(0)
    public int data() {
      return io.getIntField(this, 0);
    }

    @Field(0)
    public Nested data(int data) {
      io.setIntField(this, 0, data);
      return this;
    }
  }

  // a type with a generic nested structure.
  public static class GenericStruct<N extends StructObject> extends
      StructObject {
    @Field(0)
    public N nested() {
      return io.getNativeObjectField(this, 0);
    }

    @Field(0)
    public GenericStruct<N> nested(N nested) {
      io.setNativeObjectField(this, 0, nested);
      return this;
    }
  }

  // a concrete structure. BridgJ cannot allocate this type.
  public static class ConcreteStruct extends GenericStruct<Nested> {
  }

  @Test
  public void canCreatePointerToExtendedGenericStruct() {
    Pointer.allocate(ConcreteStruct.class).release();
  }
}

LastError not thrown

From @skyewire on July 18, 2013 17:40

LastError is often not thrown when it should be. Here is a small sample program that demonstrates the problem:

import org.bridj.*;
import org.bridj.ann.*;
import org.bridj.ann.Runtime;

public class LastErrorTest
{
    public static void main(String[] args) throws Exception
    {
        System.out.println("Registering AdvApi32");
        BridJ.register(Advapi32.class);

        System.out.println("Calling OpenServiceW with bad parameters 1");
        Advapi32.OpenServiceW(null, null, 0);
        System.out.println("Should have thrown LastError, but did not!");

        System.out.println("Calling OpenServiceW with bad parameters 2");
        Advapi32.OpenServiceW(null, null, 0);
        System.out.println("Should have thrown LastError, but did not!");
    }

    @Library("advapi32")
    @Runtime(CRuntime.class)
    private static class Advapi32
    {
        native public static Pointer<Character> OpenServiceW(
            Pointer<Character> hSCManager,
            Pointer<Character> lpServiceName,
            int dwDesiredAccess) throws LastError;
    }
}

I'm testing on Windows 7 64-bit. With the 64-bit JVM, LastError is thrown for the 2nd function call only. With the 32-bit JVM, LastError is never thrown. Sample output for both 64-bit and 32-bit JVMs:

C:\Test>"C:\Program Files\Java\jre7\bin\java.exe" -classpath .;bridj-0.6.2-windows-only.jar LastErrorTest
Registering AdvApi32
Calling OpenServiceW with bad parameters 1
Should have thrown LastError, but did not!
Calling OpenServiceW with bad parameters 2
Exception in thread "main" org.bridj.LastError: The handle is invalid. (error code = 6)
        at org.bridj.LastError.throwNewInstance(LastError.java:53)
        at LastErrorTest$Advapi32.OpenServiceW(Native Method)
        at LastErrorTest.main(LastErrorTest.java:17)

C:\Test>"C:\Program Files (x86)\Java\jre7\bin\java.exe" -classpath .;bridj-0.6.2-windows-only.jar LastErrorTest
Registering AdvApi32
Calling OpenServiceW with bad parameters 1
Should have thrown LastError, but did not!
Calling OpenServiceW with bad parameters 2
Should have thrown LastError, but did not!

The root cause of this problem is that GetLastError() is only called in Exceptions.c throwIfLastError() and this happens way too late after the actual native function call. The BridJ native code may call other Windows functions between the actual native function call and throwIfLastError(), so by the time GetLastError() is called, it is returning the error code for these other Windows functions, which will typically be 0 (succeeded). To fix, GetLastError() needs to be called immediately after the actual native function call. You don't have to deal with the error code at this stage (you can store it in a thread-local and deal with it later) but you have to store it immediately.

The same problem probably exists for errno, although I haven't tested this.

Copied from original issue: nativelibs4java/nativelibs4java#426

Demangling wrong

From @WaterFlames on November 16, 2014 13:22

Hello,
I am currently trying to wrap the C++ Steamworks library with Bridj but there seems to be a problem with the demangler.

C++ code:

class __declspec(dllexport) Glue {
public:
    static bool TESTFUNC1(ISteamMatchmaking* thisObj, CSteamID* steamIDLobby, CSteamID* steamIDInvitee);
    static bool TESTFUNC2(ISteamMatchmaking* thisObj, long steamIDLobby, long steamIDInvitee);
    static bool TESTFUNC3(ISteamMatchmaking* thisObj, CSteamID* steamIDLobby);
    static bool TESTFUNC4(ISteamMatchmaking* thisObj, long steamIDLobby);
    static bool TESTFUNC5(long thisObj, long steamIDLobby, long steamIDInvitee);
    <more unrelated functions>
};

Java code:

@Library("SteamingJavaGlue") 
public class Glue extends CPPObject {
    static {
        BridJ.register();
    }

    @Name("TESTFUNC1") 
    public static native boolean TESTFUNC1(Pointer<ISteamMatchmaking > thisObj, Pointer<CSteamID > steamIDFriend1, Pointer<CSteamID > steamIDFriend2);

    @Name("TESTFUNC2") 
    public static native boolean TESTFUNC2(Pointer<ISteamMatchmaking > thisObj, long steamIDFriend1, long steamIDFriend2);

    @Name("TESTFUNC3") 
    public static native boolean TESTFUNC3(Pointer<ISteamMatchmaking > thisObj, Pointer<CSteamID > steamIDFriend1);

    @Name("TESTFUNC4") 
    public static native boolean TESTFUNC4(Pointer<ISteamMatchmaking > thisObj, long steamIDFriend1);

    @Name("TESTFUNC5") 
    public static native boolean TESTFUNC5(long thisObj, long l1, long l2);
    <more bindings for unrelated functions>
}

The Java code is compiled using JDK 1.6 and the C++ code using Visual Studio (so MSVC I guess)
None of these functions work except for TESTFUNC3
This is the output generated by BridJ 0.7-SNAPSHOT:

INFO: DEBUG(BridJ): library="C:\SteamingJavaGlue.dll", symbol="?TESTFUNC1@Glue@@SA_NPAVISteamMatchmaking@@PAVCSteamID@@1@Z", address=ad92ac0, demangled="boolean Glue.TESTFUNC1(ISteamMatchmaking*, CSteamID*, boolean)"
INFO: DEBUG(BridJ): library="C:\SteamingJavaGlue.dll", symbol="?TESTFUNC2@Glue@@SA_NPAVISteamMatchmaking@@JJ@Z", address=ad92ae0,             demangled="boolean Glue.TESTFUNC2(ISteamMatchmaking*, CLong, CLong)"
INFO: DEBUG(BridJ): library="C:\SteamingJavaGlue.dll", symbol="?TESTFUNC3@Glue@@SA_NPAVISteamMatchmaking@@PAVCSteamID@@@Z", address=ad92b00,  demangled="boolean Glue.TESTFUNC3(ISteamMatchmaking*, CSteamID*)"
INFO: DEBUG(BridJ): library="C:\SteamingJavaGlue.dll", symbol="?TESTFUNC4@Glue@@SA_NPAVISteamMatchmaking@@J@Z", address=ad92b20,              demangled="boolean Glue.TESTFUNC4(ISteamMatchmaking*, CLong)"
INFO: DEBUG(BridJ): library="C:\SteamingJavaGlue.dll", symbol="?TESTFUNC5@Glue@@SA_NJJJ@Z", address=ad92b40,                                  demangled="boolean Glue.TESTFUNC5(CLong, CLong, CLong)"
INFO: Analyzing com.github.steamingjava.bridj.glue.Glue.TESTFUNC1
INFO: Symbol ?TESTFUNC1@Glue@@SA_NPAVISteamMatchmaking@@PAVCSteamID@@1@Z was a good candidate but expected demangled signature boolean Glue.TESTFUNC1(ISteamMatchmaking*, CSteamID*, boolean) did not match the method public static native boolean com.github.steamingjava.bridj.glue.Glue.TESTFUNC1(org.bridj.Pointer,org.bridj.Pointer,org.bridj.Pointer)

INFO: Analyzing com.github.steamingjava.bridj.glue.Glue.TESTFUNC2
INFO: Symbol ?TESTFUNC2@Glue@@SA_NPAVISteamMatchmaking@@JJ@Z was a good candidate but expected demangled signature boolean Glue.TESTFUNC2(ISteamMatchmaking*, CLong, CLong) did not match the method public static native boolean com.github.steamingjava.bridj.glue.Glue.TESTFUNC2(org.bridj.Pointer,long,long)

INFO: Analyzing com.github.steamingjava.bridj.glue.Glue.TESTFUNC3
INFO: Registering public static native boolean com.github.steamingjava.bridj.glue.Glue.TESTFUNC3(org.bridj.Pointer,org.bridj.Pointer) as function or static C++ method ?TESTFUNC3@Glue@@SA_NPAVISteamMatchmaking@@PAVCSteamID@@@Z

INFO: Analyzing com.github.steamingjava.bridj.glue.Glue.TESTFUNC4
INFO: Symbol ?TESTFUNC4@Glue@@SA_NPAVISteamMatchmaking@@J@Z was a good candidate but expected demangled signature boolean Glue.TESTFUNC4(ISteamMatchmaking*, CLong) did not match the method public static native boolean com.github.steamingjava.bridj.glue.Glue.TESTFUNC4(org.bridj.Pointer,long)

INFO: Analyzing com.github.steamingjava.bridj.glue.Glue.TESTFUNC5
INFO: Symbol ?TESTFUNC5@Glue@@SA_NJJJ@Z was a good candidate but expected demangled signature boolean Glue.TESTFUNC5(CLong, CLong, CLong) did not match the method public static native boolean com.github.steamingjava.bridj.glue.Glue.TESTFUNC5(long,long,long)

Notice that the demangled signature does not match the C++ code.

Copied from original issue: nativelibs4java/nativelibs4java#539

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.