2

Есть gradle-проект на java. В проекте используется движок jcpt, для его работы требуется подключить несколько jar-ников и нативные библиотеки (ссыль) (windiws - .dll, linux - .so). Если с .so для limux еще понятно как подобраться (смотри тут), то как подключить .dll для windows остается совсем непонятным. Как это можно сделать?

build.gradle выглядит так:

apply plugin: 'java'
apply plugin: "application"

mainClassName = "ru.cfif11.cosmo.Main"

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
version = '1.0'

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile files("jpct/lib/jpct/jpct.jar")
    compile files("jpct/lib/lwjgl-2.8.0/jar/lwjgl.jar")
    compile files("jpct/lib/lwjgl-2.8.0/jar/lwjgl_util.jar")

}

jar {
  manifest.attributes("Main-Class": mainClassName);
}

P.S. Еще лучше автоматически определять систему и прописывать пути для linux или windiws автоматически

2 ответа 2

1

Вам достаточно будет прописать команду, которая должна будет скопировать dll или so файл в папаку библиотек Java. В Linux она такая: jdk/include/linux, в Windows: jdk/include/win32. Не забываем в Java вызывать загрузку нужной библиотеки (System.loadLibrary). Та и определять не надо систему. Просто тупо копировать и одну и другую библиотеки в соотвествующие каталоги в Java.

1
  • Хм, идея неплохая, но при попытке копировать библиотеки с помощью gradle не удается, так как нет доступа. Он не может копировать что либо в папку jdk
    – 11cfif
    7 июл 2014 в 14:11
0

Я иногда использую нативные библиотеки, например, для того, чтобы создать черновик письма в MS Outlook. Выглядит это так (для Windows x64):

buildscript {
    configurations.create 'natives'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'net.sf.jacob-project:jacob:1.14.3@jar'
        natives 'net.sf.jacob-project:jacob:1.14.3:x64@dll'
    }
}

def addLibraryPath = { s ->
    try {
        // This enables the java.library.path to be modified at runtime
        // From a Sun engineer at http://forums.sun.com/thread.jspa?threadID=707176
        Field field = ClassLoader.class.getDeclaredField("usr_paths");
        field.setAccessible(true);
        String[] paths = (String[])field.get(null);
        for (int i = 0; i < paths.length; i++) {
            if (s.equals(paths[i])) {
                return;
            }
        }
        String[] tmp = new String[paths.length+1];
        System.arraycopy(paths,0,tmp,0,paths.length);
        tmp[paths.length] = s;
        field.set(null,tmp);
        System.setProperty("java.library.path", s + File.pathSeparator + System.getProperty("java.library.path"));
    } catch (IllegalAccessException e) {
        throw new IOException("Failed to get permissions to set library path");
    } catch (NoSuchFieldException e) {
        throw new IOException("Failed to get field handle to set library path");
    }
}

task createOutlookDraft {
    doLast {
        // load all DDLs from "natives" configuration for communication with Windows API
        buildscript.configurations.natives.files.each { f ->
            addLibraryPath f.parent
        }
        def outlook = new ActiveXObject("Outlook.Application")
        def newMail = outlook.CreateItem 0
        newMail.getinspector  // insert signature
        newMail.To = '[email protected]'
        newMail.Subject = "Draft"
        newMail.HTMLBody = '<body>text</body>'
        newMail.BodyFormat = 2
        newMail.Attachments.Add file('some/file.xls').toString()
        newMail.Save()
    }
}

Однако, этот вариант работает тогда, когда Вам нужно использовать DLL прямо из buildscript. В Вашем же случае скорее всего следует посмотреть вот сюда https://github.com/RobinThrift/Pathfinder/blob/master/build.gradle

import org.apache.tools.ant.taskdefs.condition.Os

...

dependencies {
    compile 'org.lwjgl.lwjgl:lwjgl:2.9.1'
    compile 'org.lwjgl.lwjgl:lwjgl_util:2.9.1'
    compile files('lib/jpct.jar')
}

platforms = ['windows', 'linux', 'osx']
platforms.each { platform ->
    task "${platform}Natives" {
        outputDir = "$buildDir/natives/$platform"
        inputs.files(configurations.compile)
        outputs.dir(outputDir)
        doLast {
            copy {
                def artifacts = configurations.compile.resolvedConfiguration.resolvedArtifacts
                    .findAll { it.classifier == "natives-$platform" }
                artifacts.each { 
                    from zipTree(it.file)
                }            
                into outputDir
            }
        }
    }
}

task natives {
    description "Copies native libraries to an appropriate directory."
    dependsOn platforms.collect { "${it}Natives" }.findAll { tasks[it] }
}

// gradle app plug-in does not allow -D options
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
    run { 
        systemProperties = [ 'java.library.path' : 'build/natives/osx;build/natives/windows;build/natives/linux', 'sun.java2d.opengl': 'true' ]
        it.dependsOn natives
    }
} else {
    run { 
        systemProperties = [ 'java.library.path' : 'build/natives/osx:build/natives/windows:build/natives/linux', 'sun.java2d.opengl': 'true' ]
        it.dependsOn natives
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.